27983	29331	sql group by with an order by	select count(id), `tag` from `images-tags` group by `tag` order by 1 desc limit 20 	0.607117506694899
30222	39122	sql server: get data for only the past year	select ... from ... where date > dateadd(year,-1,getdate()) 	0
59232	25583	how do i find duplicate values in a table in oracle?	select column_name, count(column_name) from table group by column_name having count (column_name) > 1; 	0.000392418477145674
83531	5438	sql select upcoming birthdays	select    brthdate as birthday  ,floor(datediff(dd,emp.brthdate,getdate()) / 365.25) as age_now  ,floor(datediff(dd,emp.brthdate,getdate()+7) / 365.25) as age_one_week_from_now from    "database name".dbo.employees emp where 1 = (floor(datediff(dd,emp.brthdate,getdate()+7) / 365.25))           -           (floor(datediff(dd,emp.brthdate,getdate()) / 365.25)) 	0.0668513425963462
94906	25262	how do i return random numbers as a column in sql server 2005?	select column1, column2,    abs(cast(cast(newid() as varbinary) as int)) % 10000 as column3  from table1 	0.00637892147305711
162325	16855	sql duplicate delete query over millions of rows for performance	select m.* into #temp from tl_acxiomimport.dbo.tblacxiomlistings m  inner join (select recordid,                     rank() over (partition by businessname,                                               latitude,                                                longitude,                                                          phone                                   order by webaddress desc,                                            caption1 desc,                                            caption2 desc ) as rank               from tl_acxiomimport.dbo.tblacxiomlistings            ) al on (al.recordid = m.recordid and al.rank = 1) truncate table tl_acxiomimport.dbo.tblacxiomlistings insert into tl_acxiomimport.dbo.tblacxiomlistings      select * from #temp 	0.424453682188564
189213	26336	sql selecting rows by most recent date	select   chargeid,   chargetype,   max(servicemonth) as "mostrecentservicemonth" from invoice group by chargeid, chargetype 	0
206009	16670	sql subquery	select e.*, isnull(ec.totalregistrants, 0) from events e left outer join (    select event_id, count(registrant_id) as totalregistrants    from registrant_event    group by event_id ) ec on e.id  = ec.event_id 	0.724023721825615
206735	415	a sql query that replaces null values.	select coalesce(cast(convert(varchar(10), contacttable.contactdate, 101) as varchar(10)), 'no entry') as contactdate,        coalesce(contacttable.sortname, 'no entry') as sortname,        coalesce(addresstable.city, 'no entry') as city,        coalesce(contacttable.contacttype, 'no entry') as contacttype from contacttable left outer join usertable on contacttable.userid = usertable.userid left outer join addresstable on usertable.addressid = addresstable.addressid 	0.104998459938302
211166	30204	how to get the statistics existing on a column, if any?	select s.name from   sys.objects as o        inner join sys.stats as s          on o.object_id = s.object_id        inner join sys.stats_columns as sc          on sc.object_id = s.object_id             and s.stats_id = sc.stats_id where  (o.object_id = object_id('mytable','local'))        and (o.type in ('u'))        and (indexproperty(s.object_id,s.name,'isstatistics') = 1)        and (col_name(sc.object_id,sc.column_id) = 'mycolumn') 	0.000183627732225622
269605	17532	multiple not distinct	select b, c from table where b in     (select b from table      group by b      having count(*) > 1) 	0.252759192862575
280769	30997	retrive records form one table as long as they do not exist in another table t-sql	select * from a where id not in      (select id from b) 	5.13973253150183e-05
297504	4314	way to select rows which fall on a specific day?	select * from foo where dayofweek(bar) = 2 	0
305780	34292	avg on datetime in access	select averagedate = cast(avg(cast(mydatecolumn as decimal(20, 10))) as datetime) from    mytable 	0.317851214268857
308650	40403	select x most recent non-consecutive days worth of data	select   value,   valuedate from   data where   valuedate >=    (     select        convert(datetime, min(truncateddate))     from        (          select distinct top 5             convert(varchar, valuedate, 102) truncateddate          from             event          order by             truncateddate desc       ) d   ) order by   valuedate desc 	0
312400	26642	joins and where conditions	select   `statistics`.`statisticid`,  count(distinct `flags`.`flagtype`) as `flagcount` from `statistics`  left join `flags` on `statistics`.`statisticid` = `flags`.`statisticid` where `statistics`.`statisticid`   in (select `flags`.`statisticid`     from `flags`    having count(distinct `flags`.`flagtype`) <= 3    group by `flags`.`statisticid`   ) group by `statistics`.`statisticid` order by `submittedtime` desc limit 0, 10 	0.790018697420006
325370	19940	how can i filter out the rows which contain a particular column with null or empty data in sql?	select name,age from members where name is not null and name <> '' 	0.000124172627663321
337141	18723	how do i compute an order line number in sql 2000	select      ol1.orderid,     ol1.orderlineid,     count(*) as linenumber from      orderline ol1     inner join orderline ol2       on ol1.orderid = ol2.orderid      and ol1.orderlineid >= ol2.orderlineid group by      ol1.orderid,      ol1.orderlineid 	0.11312977323252
346132	37090	postgres - how to return rows with 0 count for missing data?	select distinct date_trunc('month', (current_date - offs)) as date  from generate_series(0,365,28) as offs;           date  2007-12-01 00:00:00+01  2008-01-01 00:00:00+01  2008-02-01 00:00:00+01  2008-03-01 00:00:00+01  2008-04-01 00:00:00+02  2008-05-01 00:00:00+02  2008-06-01 00:00:00+02  2008-07-01 00:00:00+02  2008-08-01 00:00:00+02  2008-09-01 00:00:00+02  2008-10-01 00:00:00+02  2008-11-01 00:00:00+01  2008-12-01 00:00:00+01 	0.00197063705632399
365045	14716	sql question: excluding records	select itemid from table except select itemid from table where categoryid <> 12 	0.110303366258416
374846	24871	how do i select only the latest entry in a table?	select p.projectname, t.thingname from projects p join projectthinglink l on l.projectid = p.projectid join thing t on t.thingid = l.thingid where l.createddate = ( select max(l2.createddate)   from projectthinglink l2   where l2.thingid = l.thingid ); 	0
375589	4726	sparql query, select everything except things that match?	select ?husband ?color where {?husband <spouse> ?wife . ?husband <likes> ?color . optional {?wife <likes> ?wifecolor filter (?wifecolor = ?color)} filter (!bound(?wifecolor))} 	0.0200539454631709
386006	6335	how to order a sql query with grouped rows	select t2.minofpriority, tn.field2, nz([tn.field3],999) as priority,         tn.field4, tn.field5 from tn  inner join (select min(nz(tn.field3,999)) as minofpriority, tn.field2             from  tn group by tn.field2) as t2 on tn.field2 = t2.field2 order by t2.minofpriority, tn.field2, nz([field3],999); 	0.0119614205913093
415571	16561	how to combine these two queries into one? (multiple joins against the same table)	select w.*,   sum(t1.status = 1) as status_1_count,   sum(t1.status = 2) as status_2_count from workers w   left join tasks t1 on w.id = t1.worker_id and t1.status in (1, 2)  group by w.id order by w.id; 	0
435703	30804	how to select the most recent set of dated records from a mysql table	select timestamp,method,id,response from rpc_responses  inner join (select max(timestamp),method,id from rpc_responses group by method,id) latest using (timestamp,method,id); 	0
461641	32537	sql selection criteria on grouped aggregate	select customers.id from customers      left join orders as o1 on o1.customerid=customers.id and year(o1.date) = 1995     left join products as p1 on p1.id = o1.productid     left join orders as o2 on o2.customerid=customers.id and year(o2.date) = 1996     left join products as p2 on p2.id = o2.productid having sum(o1.quantity* p1.price) < sum(o2.quantity*p2.price) 	0.0814969285467311
461871	6509	find rows with non-ascii values in a column	select * from company  where ticker regexp(concat('[',char(128),'-',char(255),']')); 	0.000251752457207424
465692	40719	working out the sql to query a priority queue table	select * from queue_manager where priority_number =  (select min(priority_number) from queue_manager) and   timestamp = (select min(timestamp)  from queue_manager qm2  where qm2.priority_number = queue_manager.priority_number) 	0.456017121472343
467903	27068	how do i include filtered rowcounts from two other tables in a query of a third?	select s.id, s.classdate, s.instructor , count(distinct e.id) as enrolled, count(distinct w.id) as waiting from schedule as s left outer join enrolled as e on s.id = e.scheduleid left outer join waitlist as w on s.id = w.scheduleid group by s.id 	0
474727	32767	mysql row priority	select ifnull(cleandata, uglydata) from uglytable left outer join cleantable on clean_id = ugly_id 	0.0205989342338478
485409	10832	generating a histogram from column values in a database	select count(grade) from table group by grade order by grade 	0.00309046481796111
485581	33421	generate delete statement from foreign key relationships in sql 2008?	select 'delete '+detail.name+' where '+dcolumn.name+' = @'+mcolumn.name as stmt,      'delete ' + detail.name + ' from ' + detail.name + ' inner join deleted on ' +      detail.name + '.' + dcolumn.name + ' = deleted.' + mcolumn.name as trg from sys.columns as mcolumn  inner join sys.foreign_key_columns on mcolumn.object_id =              sys.foreign_key_columns.referenced_object_id      and  mcolumn.column_id = sys.foreign_key_columns.referenced_column_id  inner join sys.tables as master on mcolumn.object_id = master.object_id  inner join sys.columns as dcolumn      on sys.foreign_key_columns.parent_object_id = dcolumn.object_id      and sys.foreign_key_columns.parent_column_id = dcolumn.column_id  inner join sys.tables as detail on dcolumn.object_id = detail.object_id where (master.name = n'mytablename') 	0.00188045582452453
486452	25769	limiting returned record from sql query in oracle	select * from (select c.* from cool_table c    where date >= to_date('200901010000', 'yyyymmddhh24mi')     order by seq_nr, entry_dts) where rownum < 50 	0.0228400151871147
492147	22162	what's the best way to display the number of items related to tags?	select count(*) from itemtag where tagid = x 	0
504920	39431	sql tables subquery	select max(bar.timestamp), foo.foo_fluff   from foo  inner join bar           on foo.foo_id = bar.foo_id  group by foo.foo_fluff 	0.478772597438736
513098	5611	get common rows within the same table	select count(*) from votes v1 inner join votes v2 on (v1.item_id = v2.item_id) where v1.userid = 'usera' and v2.userud = 'userb' 	0
530681	26564	sql - only select row that is not duplicated	select distinct      t1.myfield1,      t1.myfield2,      t1.myfield3,      t1.myfield4,      t1.myfield5 from      mytable t1 left outer join mytable t2 on      t2.myfield1 = t1.myfield1 and      t2.myfield2 = t1.myfield2 and      t2.myfield3 = t1.myfield3 and      (           t2.myfield4 > t1.myfield4 or           (                t2.myfield4 = t1.myfield4 and                t2.myfield5 > t1.myfield5           )      ) where      t2.myfield1 is null 	0.00307368698588911
542296	33119	how to duplicate a sql server 2000 table programatically using .net 2.0?	select * into [backuptable] from [originaltable] 	0.0497385800717005
557734	29779	sql looping	select     sum(case when     (startdate is null or startdate <= '2009-01-05 00:00:00')         and (finishdate is null or finishdate >= '2009-01-05 00:00:00')     then 1     else 0 end)) week1count,   sum(case when     (startdate is null or startdate <= '2009-01-12 00:00:00')         and (finishdate is null or finishdate >= '2009-01-12 00:00:00')     then 1     else 0 end)) week2count from     tbillboards 	0.31662596758744
558283	13972	how do i find all references from other tables to a specific row?	select id, "schools" as whichtable from schools where address_id=1   union   select id, "parks" as whichtable from parks where address_id=1   union   ... 	0
560621	22154	sql convert column to row	select a as [col 1], b as [col 2] from table union all  select c,d from table  union all  select e,f from table 	0.00990563225819831
566600	40730	dynamic/conditional sql join?	select [dbo].tableb.thecolumnineed from   [dbo].tablea  left outer join [dbo].tableb on [dbo].tablea.mycolumn =     case     when [dbo].tablea.mydatecolumn <= '1/1/2009' then formatcolumnoneway([dbo].tableb.mycolumn)     else formatcolumnanotherway([dbo].tableb.mycolumn)    end 	0.62113783200868
571478	6902	sql query to select one of each kind	select color, min(id) from   mytable group by color; 	0.00125534773931933
584674	18612	how do i make this sql statement return empty strings instead of nulls?	select coalesce(datefield, '') from some_table 	0.736260970016376
586519	34962	how do i join all values from multiple rows into a single row?	select     (      select       case         when row_number() over(order by bar) = 1 then ''         else ', '       end + cast(bar as varchar)     from foo     order by bar     for xml path('')     ) 	0
590551	28365	sum columns with null values in oracle	select type, craft, sum(nvl(regular,0) + nvl(overtime,0)) as total_hours from hours_t group by type, craft order by type, craft 	0.0136202735703894
591382	16257	is it possible to use the select into clause with union [all]?	select * into tmpferdeen from (   select top 100 *    from customers   union all   select top 100 *    from customereurope   union all   select top 100 *    from customerasia   union all   select top 100 *    from customeramericas ) as tmp 	0.325912064569467
607045	3057	oracle: how to return a partial result only?	select emplid, effdt, action, action_reason from ( select emplid, effdt, action, action_reason, row_number() over (order by emplid) rn from job where emplid ='12345' ) where rn between 50 and 60; 	0.00245604862126006
628447	1346	efficient update of mysql table from sql server	select * from mysql.dbo.bank_account myb  inner join bank_account sqlb  on myb.id = sqlb.id  and sqlb.amount <> myb.amount 	0.0355226877443318
630564	21175	sql date selecting	select * from mytable where ( year(myfield) = '2009')   and ( month(myfield) = '1') 	0.0191981098769241
639341	15538	select * from table and still perform some function on a single named column	select       my_table.*,       (change_date, 'yyyy-mm-dd hh24:mi:ss') as formated_date  from my_table; 	0.00209422748338857
640179	34836	fastest way to join mysql 4.0 data from multiple tables?	select      id,      type,      convert(varchar(255), value) as value  from      table1 union select      id,      type,      convert(varchar(255), value) as value  from      table2 union select      id,      type,      convert(varchar(255), value) as value  from      table3 	0.0144037305963409
643740	40742	extension of question many to many relationships in same table	select id,hospital,doctor,patient   from table   where id in (select max(t.id) from table t group by t.hospital,t.doctor)   order by hospital,doctor; 	0.00439709405279159
666595	17614	select all that are not in another table	select distinct    old.style_nbr, old.color_nbr  from    legacy_product_table old   left outer join marketing_product_table new     on (old.style_nbr + old.color_nbr) = (new.style_number + new.colour_number) where (new.style_number + new.colour_number) is null 	0.00019660114084528
696866	39967	how do i join (merge?) several tables?	select   at.author_id,   at.author_name,   'article' as source_table,   aat.id from   author_table at   join article_author_table aat     on at.author_id = aat.author_id union all select   at.author_id,   at.author_name,   'event' as source_table,   eat.id from   author_table at   join event_author_table eat     on at.author_id = eat.author_id 	0.0262933108326996
711644	36037	sql query to exclude records if it matches an entry in another table (such as holiday dates)	select apps.applicationname, apps.isavailable  from dbo.applications apps where apps.applicationname = @appname     and not exists  ( select *    from holidays    where applicationid = apps.applicationid      and convert(varchar,getdate(),101) = convert(varchar,holidaydate,101) ) 	0
713917	487	return sql query results in separate columns sorted vertically	select     f1.data, f2.data, f3. data from (select data, row_number() over (order by data) as row_num from your_table) f1 left join (select data, row_number() over (order by data) as row_num from your_table) f2 on f2.row_num = f1.row_num + (select ceiling(count(1) / 3) + 1 from your_table) left join (select data, row_number() over (order by data) as row_num from your_table) f3 on f3.row_num = f1.row_num + (select ceiling(count(1) / 3) + 1 from your_table) * 2 where f1.row_num between 1 and floor((select count(1) from your_table) / 3) + 1 	0.00120637290215831
726152	20079	sql query - along the lines of a pivot table	select   atype,    sum(case btype when 'x' then 1 else 0 end) as x,   sum(case btype when 'y' then 1 else 0 end) as y,   sum(case btype when 'z' then 1 else 0 end) as z from   #tmp group by    atype order by    atype 	0.00112464623535505
727392	24106	how to find missing value in sequence within groups in sql?	select     above.id as id, below.position+1 as start_position, above.position-1 as end_position from missingsequence as above join missingsequence as below     on below.id=above.id and below.position<above.position-1 left join missingsequence as inbetween     on inbetween.id=below.id and inbetween.position between below.position+1 and above.position-1 where inbetween.id is null; + | id | start_position | end_position | + | 44 |              2 |            2 |  + 	0.000780631403265993
748229	24632	sql - getting more data with a group by	select      i.serial_number, i.counter, i.selected_color from    (    select      serial_number, max(counter) as maxc    from            incoming_data     group by    serial number    ) max    join    incoming_data i on max.serial_number = i.serial_number and max.maxc = i.counter 	0.11100322478418
755918	4771	simple query to grab max value for each id	select cur.id, cur.signal, cur.station, cur.ownerid from yourtable cur where not exists (     select *      from yourtable high      where high.id = cur.id      and high.signal > cur.signal ) 	5.65511410470927e-05
757146	29696	mix xml parents and children in mssql	select      thexml.thecookie.value('(id[1])', 'varchar(20)') as cookiename    , thexml.thecookie.query('.') as cookiedata    , sub.subcookie.value('local-name(.)', 'varchar(20)') as subcookiename from    @xmlcon.nodes(' cross apply     thexml.thecookie.nodes('./*') as sub(subcookie) 	0.0775017482613621
760950	31073	how to do a select in a select	select * from yourtable y where not exists       (select * from othertable o where y.ref = o.ref) select * from yourtable where ref not in       (select ref from othertable where ref is not null) select y.* from yourtable y  left outer join  othertable o on y.ref = o.ref where o.ref is null 	0.0360394625571136
769475	13007	sql to join one table to another table multiple times? (mapping products to categories)	select   p.name,   group_concat(c.name separator ', ') as categories from   product p   join product_to_category pc on p.id = pc.product_id   join category c on c.id = pc.category_id group by   p.name order by   p.name,   c.name 	0
774644	17195	sql server 2000 drop column with constraints	select      col.name,      col.colorder,      col.cdefault,      objectproperty(col.cdefault, n'isdefaultcnst') as is_defcnst,      dobj.name as def_name from syscolumns col      left outer join sysobjects dobj          on dobj.id = col.cdefault and dobj.type = 'd'  where col.id = object_id(n'dbo.table_name')  and dobj.name is not null 	0.215152951842928
777861	38423	set based calculation for events table, exceptuating an event	select    [delay_start].event_id,    sum(datediff(second, [delay_start].date, [delay_finish].date)) from    event_table as [delay_start] inner join    event_table as [delay_finish]       on  [delay_finish].event_id = [delay_start].event_id       and [delay_finish].date = (                                  select                                     min(date)                                  from                                     event_table                                  where                                     event_id = [delay_start].event_id                                     and date > [delay_start].date                                     and event = 'service reactivated'                                 ) where    [delay_start].event = 'service delayed'    and [delay_finish].event = 'service reactivated' group by    [delay_start].event_id 	0.000502019792259847
778245	27092	determine active node in sql failover cluster	select serverproperty('computernamephysicalnetbios') 	0.0677745548165204
780265	27044	create xml file from sql script	select * from table for xml path  set @sql= 'bcp "exec dbname.dbo.table" queryout c:\myfile.xml -w -r -t -sservername -t' exec master..xp_cmdshell @sql 	0.105942826623725
794146	34940	sql: efficiently look up many ids coming from outside the db	select were in 	0.00105745536959664
809124	6252	finding breadcrumbs for nested sets	select groupid,    (level1      + case when level2 is not null then ' > ' + level2 else '' end     + case when level3 is not null then ' > ' + level3 else '' end    )as [breadcrumb] from (   select g3.*     ,g1.name as level1     ,g2.name as level2     ,g3.name as level3   from @toplevelgroups g1   inner join @usergroups g2 on g2.parentid = g1.groupid and g2.groupid <> g1.groupid   inner join @usergroups g3 on g3.parentid = g2.groupid    union   select g2.*     ,g1.name as level1     ,g2.name as level2     ,null as level3   from @toplevelgroups g1    inner join @usergroups g2 on g2.parentid = g1.groupid and g2.groupid <> g1.groupid   union   select g1.*     ,g1.name as level1     ,null as level2     ,null as level3    from @toplevelgroups g1 ) a order by [breadcrumb] 	0.280322680625337
813057	25149	sql server except	select person_uid, instype     from admitsinterfacetable a     where instype='i'   union   select person_uid, instype     from admitsinterfacetable a     where instype='m'      and not exists (        select * from from admitsinterfacetable b      where instype='i' and b.person_uid = a.person_uid); 	0.385168302622649
818099	35602	using multiple tables, multiple values with min() sql	select sum(min(fp-20, ap)) from   (select dates.pk as fd, sum(points) as fp   from dates   join foods on name_id = fd   group by fd   having fp >= 20)     join   (select dates.pk as ad, sum(activity) as ap   from dates   join activities on activity_id = ad   group by ad)     on fd = ad 	0.0209060951794506
820219	24476	how to find slowest queries	select  creation_time          ,last_execution_time         ,total_physical_reads         ,total_logical_reads          ,total_logical_writes         , execution_count         , total_worker_time         , total_elapsed_time         , total_elapsed_time / execution_count avg_elapsed_time         ,substring(st.text, (qs.statement_start_offset/2) + 1,          ((case statement_end_offset           when -1 then datalength(st.text)           else qs.statement_end_offset end             - qs.statement_start_offset)/2) + 1) as statement_text from sys.dm_exec_query_stats as qs cross apply sys.dm_exec_sql_text(qs.sql_handle) st order by total_elapsed_time / execution_count desc; 	0.0376558152557462
854747	14300	is there a way i can make the case when test one of the results rather than running it twice?	select     orderid,     case when maxprice is null then 0 else maxprice end as maxprice from (     select         orderid = o.id,         maxprice = (select max(price) from orderlines ol                      where ol.orderid = o.id)     from orders o ) sub 	0.39406461302696
855834	22431	determining items that join against the same set in t-sql	select distinct o1.orderid  from orders o1 inner join orders o2 on o1.orderid!=o2.orderid where not exists     (      select * from [order details] od2      where od2.orderid=o2.orderid       and od2.productid not in        (        select productid from [order details] od1        where od1.orderid=o1.orderid       )     )     and not exists     (      select * from [order details] od1      where od1.orderid=o1.orderid       and od1.productid not in        (        select productid from [order details] od2        where od2.orderid=o2.orderid       )     ) 	0.000764646932070128
857007	3046	group by, order by - how to make group by consider latest apperance of item	select    p.p_pid,    p.p_name,    p.p_url  from products p  inner join activity a on p.p_pid = a.a_pid  where    a.a_uid= ".$uid_int."  group by    p_pid, p_name, p_url order by    max(a.a_time) desc    limit 6 	0.000456973266393394
857942	1617	how can i get the field names of a database table?	select * from information_schema.columns  where table_name='yourtablename' order by ordinal_position 	0
858648	38731	disappearing stored procedure	select syo.name from syscomments syc     join sysobjects syo on         syo.id = syc.id where syc.[text] like '%drop proc%' 	0.786755269965428
859255	28462	prevent oracle minus statement from removing duplicates	select a, b, c from table1 where (a,b,c) not in (     select a,b,c from table2 ) 	0.418650920324944
878376	34870	sql query to join several columns	select     t.desc, s1.desc, s1.aaaaa, s2.desc, s2.aaaaa, s3.desc, s3.aaaa     from table2                t         left outer join source s1 on t.id1 = s1.id         left outer join source s2 on t.id2 = s2.id         left outer join source s3 on t.id3 = s2.id     where t.id=@youridhere 	0.0996818852710295
885188	30625	specific time range query in sql server	select *   from mytable   where [datecolumn] > '3/1/2009' and [datecolumn] <= dateadd(day,'3/31/2009',1)      and datepart(hh,[datecolumn]) >= 6 and datepart(hh,[datecolumn]) <= 22      and datepart(dw,[datecolumn]) >= 3 and datepart(dw,[datecolumn]) <= 5  	0.0113319667872077
885725	7015	how do i select all the rows where a varchar field contains non-digit characters?	select * from yourtable where isnumeric(yourfield) = 0 	0
889629	30734	how to get a date in yyyy-mm-dd format from a tsql datetime field?	select convert(char(10), getdate(),126) 	0
902259	37676	how do you count outside of the where statement in mysql	select a, (select count(*) from t t2 where t2.a = t.a) a_count from t where b in (1,2) group by a 	0.102761525822804
906371	37996	executing sql query after particular point iof time	select * from receivedsms where timerecieved < dateadd(second, -180, getdate()) and       postprocessed = 0 foreach record - execute sproc & update postprocessed = 1. 	0.257839761221465
912078	32871	mysql: how to write a query for a relationship that is based on a range, not a foreign key?	select * from user as u inner join level as lv on     u.karma >= lv.min_karma and u.karma <= lv.max_karma inner join levelclass as lvc on     lv.num >= lvc.min_level and lv.num <= lvc.max_level 	0
925124	26601	how do i create a customary ranking of my result set in sql?	select top(1)     t.dayid from (         select             dayid,             case                 when dayid = 3 then 1                  when dayid = 4 then 2                  else 3             end dayrank         from             tdaychores dc             inner join tchore c                 on c.choreid = dc.choreid         where             c.choredescription = 'vacuum'     ) t order by t.dayrank 	0.135803119162734
940189	17212	dynamically finding column values in a trigger from insert when the column name is a variable	select * into #myinserted from inserted exec('select * from #myinserted') drop table #myinserted 	5.50248421932742e-05
966782	4404	how do i use a left join twice on the same colum with mysql?	select     routes.*,     a1.name as origin_name,     a2.name as destination_name from routes r left join airports a1 on a1.iata = r.origin left join airports a2 on a1.iata = r.destination where     r.origin = 'lhr' and r.destination = 'vce' or r.origin = 'vce' 	0.058431727762898
970738	17526	sql query to find single, sorted record	select top 1 * from table where applydate <= '4/15/2008' and (startdate is null or startdate<= '4/15/2008') and (enddate is null or enddate >= '4/15/2008') and extid = '101' order by  applydate desc 	0.000195654428541628
978093	6189	sql query to get a row, and the count of associated rows	select a.id, a.title, count(c.id) as numcomments from articles a left join comments c on c.parentid = a.id group by a.id, a.title 	0
982464	10135	distinct popular hits	select name, imdb, id, owner, count from  (  select su.name,su.imdb , su.id, su.owner, count(*) as count   from subhits as h left join subtitles as su on h.subid=su.id   where su.added between '" . $lweek . "' and '" . $today . "'   group by h.subid  order by count desc ) group by imdb limit 15 	0.0128525923870653
984396	24266	how to get mysql random integer range?	select id, (floor( 1 + rand( ) *60 )) as timer from users limit 0 , 30 	0.000408954578371492
997619	13981	sccm query: how to get latest user-logon registration (if any) and display pc, ip, user, logontimestamp	select sv.netbios_name0 as [netbios name]        , latest_user.systemconsoleuser0 as [user name]        , cast(isnull(scu.thelasttime, 0) as datetime ) as [last console use]        , ip.ip_addresses0 from   v_r_system_valid sv         left outer join                  (select  resourceid                           ,max(lastconsoleuse0) as thelasttime                   from     v_gs_system_console_user                   group by resourceid                           ,systemconsoleuser0) as scu         on scu.resourceid = sv.resourceid        left outer join v_gs_system_console_user as latest_user        on latest_user.lastconsoleuse0 = scu.thelasttime    and        latestuser.resourceid = scu.resourceid        left outer join v_ra_system_ipaddresses as ip        on ip.resourceid = sv.resourceid where  (sv.netbios_name0 not like 'enc-%')      and         (sv.netbios_name0 not like 'nl%') order by sv.netbios_name0 	0.000212938070711695
1013662	29285	best practice to querying a lookup table	select * from property where  exists (select * from property_feature where pid = property.pid and fid = 'key_air_conditioning') and exists (select * from property_feature where pid = property.pid and fid = 'key_pool') 	0.0423159804907809
1016804	35890	how to sort mysql fulltext search results by relevancy	select * from vocabulary  where translation like 'word'   union all select * from vocabulary  where translation like '%word%' and translation not like 'word' 	0.517500822842451
1038506	26668	efficient way of getting @@rowcount from a query using row_number	select      row_number() over(order by object_id, column_id) as rownum     , count(*) over(partition by 1) as totalrows     , *      from master.sys.columns 	0.283349836360048
1049929	39482	oracle 11g sql select max integer value of varchar column	select max(to_number(unid)) from yourtable 	0.00217267681392126
1051927	11246	sql to find most popular category	select c.name, sum(abs(v.item_id))   from categories c,items i, votes v  where c.name = i.name     and i.item_id=v.item_id  group by c.name   order by sum(abs(v.item_id)) desc limit 5; 	0.000168732498646743
1058370	24135	how to do sorting in sql server varchar types	select strorevals  from tblswap  order by right(replicate('0', 11) + strorevals, 10) 	0.187855262727906
1062751	3095	getting min price in subquery in sql server (using distinct)?	select         datepart(year,[registration]) as yearregistered,         min(saleprice), model, make from         [vehiclesales]  group by         datepart(year,[registration]), model, make 	0.130595827895014
1062982	34886	how to get sum slalry year by year using sql query?	select         aid,year,         salary=(select sum(slalry) from slalry where year<=a.year)     from slalry as a; 	0.000269876213315536
1066381	23639	sql - joining on multiple columns in the same row	select dd.degreedesc, dd1.degreedesc from degreehistory dh left join degreedescription on degreecode = dh.major1 dd left join degreedescription on degreecode = dh.major2 dd1 ... 	4.63658433490745e-05
1067171	13483	sql select statement that shows non-existant column?	select c1, c2, c3, null as c4 from table; 	0.207106926273818
1068087	30056	how can i tweak this sql to perform the arithmetic calculation only once	select calc.amtpercent   from ( select (amount1-amount2)/cast(amount1 as float) as amtpercent from z8test) calc  where calc.amtpercent > 1 or calc.amtpercent < 0.3 select (amount1-amount2)/cast(amount1 as float)  as amtpercent   from z8test  where (amount1-amount2)/cast(amount1 as float)  > 1     or (amount1-amount2)/cast(amount1 as float)  < 0.3 select (amount1-amount2)/cast(amount1 as float)  as amtpercent   from z8test  where (amount1-amount2)/cast(amount1 as float)  not between 0.3 and 1 	0.530057616169656
1081851	14524	mysql: query to get previous and next video id?	select *    from videos as c   where (videoid = (select max(videoid) from videos where videoid < c.videoid and isactive = 1)     or  videoid = (select min(videoid) from videos where videoid > c.videoid and isactive = 1)) 	7.73178612376846e-05
1091746	4948	how to concatenate values from mysql select	select group_concat(bar) from table group by foo; 	0.000272814978849137
1098989	16347	sql combining union and except	select  coalesce(sub1.id, sub2.id), coalesce(sub1.date, sub2.date) from    sub1 full outer join         sub2 on      sub1.id = sub2.id 	0.246431305932831
1105463	1496	sqlite binding within string literal	select * from table where title like '%' || ? || '%'; 	0.668264382318105
1113896	23817	group by id range?	select    floor(id / 5) ym,    count(result) 'total games',     sum(result) as 'score' from nn_log group by ym; 	0.00341664295165011
1123680	33727	display the active member details	select username, password  from userstable where isactive > 0 and username = 'admin' and password = '1234' 	0.000177962506054813
1131467	31950	programmatically replace select fields in sql query to determine number of results	select count(*) from (<original select query>) 	0.0161403808511588
1145078	33409	mysql random rows sorted by a column name	select * from (select * from categories order by rand() limit 3) c order by name 	6.69888614261023e-05
1145228	29418	how do i write a sql query with a condition involving a second table?	select t1.*   from table1 t1   join table2 t2 on t2.thresholdid = t1.thresholdid  where t2.threshold > t1.value 	0.0728250889047753
1173287	15875	sql server query with complex calculations for every row	select cola2,  case when cola2 = colb1 and colb4 = colc12 then colb2 else null end as calculation1,  case when cola2 = colb1 and colb5 = colc3 then colb3 else null end as calculation2,  (colb3 - colb2) * size * factor1 as calculation3, <...> into #intermediate from tablea  inner join tableb on <...> inner join tablec on <...> select sum(calculation3) as sumcalculation3, avg(calculation3) as avgcalculation3 from #intermediate 	0.386789945568376
1184499	40424	how do i produce a time interval query in sqlite?	select strftime('%y-%m-%dt%h:%m:00.000',start_ts) time_interval,      (select count(session_id)        from sessions s2        where strftime('%y-%m-%dt%h:%m:00.000',s1.start_ts) between s2.start_ts and s2.end_ts) active_sessions    from sessions s1    group by strftime('%y-%m-%dt%h:%m:00.000',start_ts); 	0.142043108176393
1186227	38966	sql: selecting parents and their children	select q.text, a.text from questions q left join answers a on      q.quiestionid = q.id group by q.id, a.id order by q.id 	0.000227958776438837
1187591	40396	is there any way to alter a column to switch off 'not null'?	select    'alter table ' + table_name + ' alter column ' + column_name + ' ' + data_type from information_schema.columns  where table_name = 'xxx' 	0.618552398494542
1196063	26033	multiple mysql select queries	select * from location where food='pizza'   and zip in(90210, 55555, etc..) 	0.208078573951134
1215346	22903	sql query for top 5 of every category	select t1.category, t1.timestamp, t1.value, count(*) as latest from foo t1 join foo t2 on t1.id = t2.id and t1.timestamp <= t2.timestamp group by t1.category, t1.timestamp having latest <= 5; 	0.000200684147185654
1218276	267	advanced sql select	select id, value from tbl2 where tbl2.id not in (    select tbl2-id    from table3    where (user = <this user>) and (tbl1-id = <selected tbl1 id>)    ) 	0.6934074191671
1225658	24048	php/mysql / use string to select from database	select usrfirst, usrlast from tblusers where usrid in ($string) 	0.0254688882474419
1238277	8314	how to get hours from subtracting two date time values in sql server 2005	select  datediff(hour, '2009-08-06 00:00:00', '2009-10-06 23:59:59')  71 	0
1245908	14820	sql server: sort a column numerically if possible, otherwise alpha	select     *     from yourtable     where isnumeric(yourcolumn)=1     order by yourcolumn 	0.0560703752946367
1258779	11963	get list of parent and child records with multiple entries with criteria - sql 2005	select * from child where id_specmatrix in (4,5) and       parent_id in (select distinct parent.id from parent p                     join child s1 on s1.id_parent = p.id and s1.id_specmatrix = 4                     join child s2 on s2.id_parent = p.id and s2.id_specmatrix = 5) 	0
1262683	2139	grouping data from multiple tables	select everything.duration, count(*) from ((select timestampdiff(hour,starttime,endtime) as duration   from feb where type='gen')  union all  (select timestampdiff(hour,starttime,endtime) as duration   from apr where type='gen')  union all  (select timestampdiff(hour,starttime,endtime) as duration   from oct where type='gen')  union all  (select timestampdiff(hour,starttime,endtime) as duration   from dec where type='gen')) everything group by everything.duration into outfile "/all"; 	0.00345193094622055
1263865	35391	how to select all values, not just those in where clause	select id, type from  (select id, group_concat(type separator ',') as type from rock_types          group by id) a where instr(type,"dws")>0 or instr(type,"top rope")>0 	0.00207281506069286
1266666	27515	using union and count(*) together in sql query	select tem.name, count(*)  from(select name from results union all select name from archive_results) as tem group by name order by name 	0.636741545347838
1278609	23016	sql server : find last time user was connected	select accdate, name from master.dbo.syslogins 	0.000180343094338776
1282644	36224	use the result of one mysql command in another mysql command?	select e2.id from mm_eventlist_dates e1 join mm_eventlist_dates e2 on e2.startdate = date_add(e1.enddate, interval 1 day) where e1.id=$id 	0.01780038869251
1283787	17542	select top one from left outer join	select    user_table.userid,    user_table.username,    isnull(hitstable.browser, 'unknown') as browser from   user_table left join (   select     userid,     max(hitsdate) hitsdate   from     hits_table   group by       userid ) latest_hits on   user_table.userid = latest_hits.userid     left join   hits_table on hits.table.userid = latest_hits.userid and hits_table.hitsdate = latest_hits.hitsdate 	0.154357118160904
1289178	30583	search column in sql database ignoring special characters	select     artist,     title from     songs where     replace(replace(replace(artist, '#',''), '*', ''), '"', '') like '%keywords%' 	0.186765290543152
1295087	3564	calculating a row position in the table	select count(*) from media where rating > (select rating from media where id = 5); 	0.000580726187290204
1295572	35340	how can i find every row in a table where the value of a field is contained in a specific string?	select * from names where 'bob marley' like concat('%', firstname, '%') 	0
1316366	7075	normalised beyond my sql knowledge?	select max(break_score) maxbreak, avg(break_score) avgbreak, count(break_score) breaks from breaks join matches on match_id=break_match where exists(select 1 from players join team_members on player=player_id and team=3 where break_year = year and break_player = player_id and (match_hometeam=3 or match_awayteam=3)) 	0.771129559039716
1326195	28832	sql find possible duplicates	select t1.* from  t as t1 left join t as t2  on (t1.date2=t2.date2 and t1.groupid=t2.groupid) where t1.id != t2.id and (t1.date1='1900/01/01' or t2.date2='1900/01/01') 	0.08544760009837
1338647	39695	check combination of records in table	select * from (select * from (select distinct col1 from table1) cross join (select distinct col2 from table1)) as t1 left outer join table1 on t1.col1 = table1.col1 and t1.col2 = table1.col2 where table1.col1 is null 	0.000406329804331655
1342849	20863	combining two mysql select statements so i can sort the resulting data	select domains.domainid, domainname, count(*), sum(uniqueuploads) from domains inner join files on files.domainid = domains.domainid inner join serverfiles on serverfiles.fileid = files.fileid group by domains.domainid, domainname 	0.00746278744322574
1342983	7364	sql distinct count with an exception	select count(distinct floor) as nb_floors from table_id where floor <> 'b' 	0.701610463281462
1348712	17184	creating a sql server table from a c# datatable	select * into <tablename> from @tvp 	0.0884205014103275
1353099	5363	sql query, selecting 5 most recent in each group	select c1.* from codes c1 left outer join codes c2   on (c1.language_id = c2.language_id and c1.time_posted < c2.time_posted) group by c1.id having count(*) < 5; 	0
1358465	8716	handle precision difference in oracle	select ...    case       when percentile_disc(0.9999)            within group(order by duration_count)            < 100000000       then percentile_disc(0.9999)            within group(order by duration_count)       else null    end as percentile_9999_qty, ... 	0.0858012970020653
1364886	39014	what is the easiest way to export a sqlserver 2000 database to xml?	select * from {tablename} for xml auto 	0.784747869816862
1367101	31320	retrieving key attribute names of a given table	select       cols.table_name              , cols.column_name              , cols.position              , cons.status              , cons.owner from         all_constraints cons              , all_cons_columns cols where        cols.table_name = 'table_name' and          cons.constraint_type = 'p' and          cons.constraint_name = cols.constraint_name and          cons.owner = cols.owner order by     cols.table_name, cols.position; 	0
1369551	19989	list of tables without indexes in sql 2008	select       schemaname = object_schema_name(o.object_id)     ,tablename = o.name from sys.objects o inner join sys.indexes i on i.object_id = o.object_id where (         o.type = 'u'         and o.object_id not in (             select object_id             from sys.indexes             where index_id > 0             )         ) 	0.116362635552245
1387804	35258	how to display all the record by date wise?	select a.personid, b.date from (select distinct personid from mytable) a,  (select distinct date from mytable) b 	0
1397471	38864	simple query to get group results	select deptid, max(createdate) from depts where [status] = 'y' group by deptid 	0.421640715381283
1403237	36095	migrating mysql to a table with different structure	select 'insert into new_table ... ('+ to.column +');'   from old_table ot 	0.0414048228925365
1416310	10170	how can i take the results of two database rows and condense them into a single row?	selectc.name,  c.address1,  p.ptype,  p.phone,  p2.ptype,  p2.phone,  fromcustomer as cinner   join customeremp as e on   c.customer_id = e.customer_idinner   join customerphone as p on e.customer_seq = p.customer_seq and p.ptype = 1 (or whatever private means)  join customerphone as p2 on e.customer_seq = p2.customer_seq and p2.ptype = 2 (or whatever the other type is)  wherec.customer_id =  '1' 	0
1418128	39762	sql query with 2 grouping	select s.idsplit,      count(case when v.vote > 0 then 1 else null end) as voteup,      count(case when v.vote < 0 then 1 else null end) as votedown  from cc_split s left join cc_split_usager as v on v.idsplit = s.idsplit where s.isarchived = false group by s.idsplit limit 0, 30 	0.24638934850808
1424978	33709	display column alias from other tbl	select tbl2.userid, tb2.col3 as [your name here], tbl1.col1 as [your name here], ... from tbl2 inner join tbl1 on tbl1.userid = tb2.userid where tbl2.userid = "testuser" 	0.0020382615496482
1436747	18214	how can you find the rows with equal columns?	select *  from foo first join foo second   on ( first.a = second.a        and first.b = second.b )    and (first.id <> second.id ) 	0.00013191399793177
1441316	20253	sql query: get tag id and number of tag occurences	select tag_id,           count(article_id) as article_count      from article_tags  group by tag_id 	0
1455943	31987	retrieving rows with the highest value	select id, max(cost) maxcost from #table group by id 	0
1456106	3913	how to select an empty result set?	select     1 from     dual where     false 	0.0480115731432812
1464014	39226	db2: accessing the column by column number	select colname, colno, typename, nulls from syscat.columns         where tabschema = ? and tabname = ? order by colno 	0.000497609515870968
1468807	11984	how to cast datetime as a date in mysql?	select * from follow_queue group by date(follow_date) 	0.0449274576325644
1471523	13597	select only rows that contain only alphanumeric characters in mysql	select * from table where column regexp '^[a-za-z0-9]+$' 	6.49117361641084e-05
1492431	10463	return all fields and distinct rows	select b.* from (     select max(id) id, name, address     from table a     group by name, address) as a inner join table b on a.id = b.id 	0.00015492408355297
1504666	6431	mysql: how to store/retrieve artist information?	select title, yearproduced, name, profilepage from tblsongs  s left outer join tblsongartists sa on sa.songid = s.songid left outer join tblartists a on a.artistid = sa.artistid where title = 'i got the blues'   order by songid   	0.0910854486518408
1505629	19636	sql server 2008 - find table with most rows	select      [tablename] = so.name,      [rowcount] = max(si.rows)  from      sysobjects so,      sysindexes si  where      so.xtype = 'u'      and      si.id = object_id(so.name)  group by      so.name  order by      2 desc 	0.00176960380216776
1507033	22092	how to have more than one condition for data recall	select *  from `banner`  where if(`type` = 'event', `when` > now(), 1)  order by `when` desc 	0.00190351268884068
1515749	36810	mysql query related problem	select subquery.bank_name, sum(subquery.amount) from     (     select bank_name, sum(amount) as amount from accounts_bank ab left join bank b on         b.bank_id=ab.bank_id where method=0 group by bank_name     union all     select bank_name, sum(-amount) as amount from accounts_bank ab left join bank b on         b.bank_id=ab.bank_id where method=1 group by bank_name     ) as subquery group by subquery.bank_name order by subquery.bank_name 	0.664301605232496
1518421	15217	how shall i get my friends of friends using mysql and php	select * from tbl_friendlist where mem_id in (select friend_id from tbl_friendlist where mem_id = 1). 	0.000858813471911701
1531367	38806	how to compare a date with system date?	select 'today is the last day for ' + id  from (select id, max(date) as date from table1) t1 where datepart(dayofyear, date) = datepart(dayofyear, getdate())  and datepart(year, date) = datepart(year, getdate()) 	0.00447571574314691
1531641	39789	sql server query - find first in sequence	select m1.groupid, m1.itemid, m1.created  from mytable m1 join  (select groupid,min(created) as created from mytable) m2  on m1.groupid = m2.group_id  and m1.created = m2.created 	0.0148392970738989
1538835	28470	using aggregate function with more than two columns	select     distinct on (stat_id)     * from     stat_log where     user_id = 1 order by stat_id desc, registered_desc; 	0.193415256379412
1547301	29625	sql server - distinct value from multiple(2) columns	select a from yourtable      union       select b from yourtable 	0.00103132112671856
1550294	30665	help with another mysql query	select count(xbrygame_scrnsmkv.id) from xbrygame_scrnsmkv  where xbrygame_scrnsmkv.id >(select  max(xbrygame_scrnsmkv.id)                               from xbrygame_scrnsmkv                               where xbrygame_scrnsmkv.product_id= (select  distinct xbrygame_scrnsmkv.product_id                                                               from xbrygame_scrnsmkv                                                               order by xbrygame_scrnsmkv.id desc limit 5,1))     group by xbrygame_scrnsmkv.product_id 	0.71625035285966
1554025	14099	monthly breakdown of table data, date stored as epoch time	select  year(from_unixtime(mycolumn)) as yr,         month(from_unixtime(mycolumn)) as mon,         count(*) from    mytable group by         yr, mon 	0.000599452935274269
1554793	19130	how to do a select on like values from multiple columns in sql	select genre as result from genres where genre like '%ep%' union select adjective_title as result from    adjectives where adjective_title like '%ep%' 	0.000475459066541818
1555151	38920	convert "flat" sql query result into table structure	select 'amount' as maxamount, [group1], [group2], [group3]   from (select descrip, amount      from table) as sourcetable pivot ( max(amount) for descrip in ([group1], [group2], [group3]) ) as pivottable; 	0.0515761799958999
1557067	13142	calculating consecutive absences in sql	select a.*,       (       select min(b.absencedate) from tblabsences b where a.employeeid = b.employeeid        and b.absencedate >= a.absencedate       and not exists (         select 1 from tblabsences c where c.employeeid = b.employeeid and dateadd( dd, 1, b.absencedate) = c.absencedate         ) ) consecdates from dbo.tblabsences a order by a.absencedate asc 	0.0530708471249675
1560626	33209	sqlserver: how to pair up ordered data for sequences of arbitrary (and unequal length)?	select      coalesce(a.fkid, b.fkid) fkid,      a.value as valuea,      b.value as valueb,      coalesce(a.sort, b.sort) sort from a full outer join b      on a.fkid = b.fkid      and a.sort = b.sort order by fkid, sort 	0.000455013887847955
1565278	39248	sql server: find out which users have write access to which tables?	select u.name, o.name from syspermissions p, sysobjects o, sysusers u where p.id = o.id and u.uid = p.grantee and u.name in ('userone', 'usertwo', 'userthree') and o.xtype = 'u' and p.actadd = 27 	0.00191466039139344
1565688	14124	how to get the max of two values in mysql?	select greatest(2,1); 	0
1576192	18755	numeric string (arbitrary size) -> multiple integers	select (mybigintfield & 0xffffffff) as lowerhalf,        (mybigintfield >> 32) as upperhalf 	0.0159965685658373
1591888	34851	sql query to get content older than 3 weeks	select contentid, title, created  from content where created < dateadd(week,-3,getdate()); 	0.000200985669982044
1602234	38880	is there sql notation that can tell check between months?	select * from tbl where (month_from <= $your_month and month_to >= $your_month) or        (month_from > month_to and (month_to >= $your_month or month_from <= $your_month) 	0.0231007058453768
1607885	8269	adding some logic to sql query	select a.personid from abilities a join abilities b on (a.personid = b.personid and b.text = 'drive') join abilities c on (a.personid = c.personid and c.text = 'sing') left join abilities d on (a.personid = d.personid and d.text = 'flight') left join abilities e on (a.personid = e.personid and e.text = 'skateboard') where a.text = 'fly' and d.id is null and e.id is null 	0.726065377111012
1609725	6158	mysql 2 queries in one?	select * from toovague; select * from googleit; 	0.0190659009842038
1637161	26657	top 2 values from group by	select  details,         (         select  id         from    test ti         where   ti.details = to.details         order by                 date         limit 1         ) as first_id from    test to group by         details 	0.000484856441888007
1661452	18513	how do i make a category for each unique db entry? (mysql/php)	select votedon, count(*)  from voting_table group by votedon 	0
1668287	19820	sql query to fetch number of employees joined over a calender year, broken down per month	select   trunc(emp_jn_dt,'mm') emp_jn_mth,          count(*) from     emp_reg where    emp_jn_dt between date '2009-01-01' and date '2009-12-31' group by trunc(emp_jn_dt,'mm') order by 1; 	0
1673802	17930	multiple max values in a query	select id, bdate, value  from myview  where (id, bdate) in     (select id, max(bdate)      from myview group by id) / 	0.0249978204243853
1674632	11043	t-sql table join	select lefttable.* from lefttable     inner join righttable         on lefttable.id = righttable.id 	0.345520204328866
1674726	23125	lots of queries to pull up user photos and their comments. (cakephp)	select c.text, i.profiles, p.photo_url from comments as c left join profiles as i on c.profile_id = i.id left join photos as p on i.id = p.user_id where c.post_id = 32 limit 20 	0.000355922510515707
1674964	16613	sql return unique data	select * from  (select   id,    col1,    col2,    col3,   row_number() over(partition by col1 order by col3) nom from table_name) a where a.nom = 1 	0.0105806428065083
1688065	34601	including not found criteria in the result	select criteria.bunit, t.value  from (     select 555 as bunit from dual     union select 556 from dual     union select 557 from dual     union select 558 from dual ) criteria left join mytable t      on t.bunit = criteria.bunit 	0.0301373625579172
1753837	30081	unknown column {0} in on clause	select `puzzlecategories`.`puzzlecategory`, `clients`.`businessname`, `puzzles`.`puzzlenumber` from `clients` inner join `publications` on `clients`.`clientid` = `publications`.`clientid` inner join `publicationissues` on `publicationissues`.`publicationid` =   `publications`.`publicationid` inner join `puzzleusages` on`puzzleusages`.`publicationissueid` = `publicationissues`.`publicationissueid` inner join `puzzles` on `puzzles`.`puzzleid` = `puzzleusages`.`puzzleid` inner join `puzzlecategories` on `puzzles`.`puzzlecategoryid` = `puzzlecategories`.`puzzlecategoryid` 	0.571979372845483
1758729	13936	collapsing null values in oracle query	select distinct        id,        max(time_in) over (partition by id),        max(time_out) over (partition by id) from (...) 	0.22990012738142
1762312	38887	select query in sql server 2008	select c.id, c.name, p.name, p.pointid, p2.pointid, p2.name from tblchildinfo c join tblpoint p on c.pickuppointid = p.pointid join tblpoint p2 on c.dropdownpointid = p2.pointid where <insert where clause> 	0.786977366876309
1765040	32085	mysql fetch 10 posts, each w/ vote count, sorted by vote count, limited by where clause on posts	select p.*, count(*) yes_count from posts p left outer join votes v on (v.post_id = p.id and v.vote_type_id = 1) where p.is_hidden = 0 group by p.id order by yes_count desc limit 0,10 	0
1782557	38380	retrieve multiple records based on multiple and where conditions	select ... where ... union select ... where ... union select ... where ... 	0
1785838	20675	mysql foreach child show max() and min() in a single line	select p.id, max(c.a), min(c.a) from parent as p left outer join child as c on c.parentid = p.id group by p.id; 	0.000630933113396058
1789296	8137	how to search for text in sql server when storing different languages	select      product_name  from      products  where      product_name collate sql_latin1_general_cp1_ci_ai like 'chateau' 	0.175175462166316
1793054	9064	select top 1 with a group by	select max_table.namecode, count_table2.name from     (select namecode, max(count_name) as max_count      from          (select namecode, name, count(name) as count_name           from mytable           group by namecode, name) as count_table1      group by namecode) as max_table inner join     (select namecode, count(name) as count_name, name      from mytable      group by namecode, name) count_table2 on max_table.namecode = count_table2.namecode and    count_table2.count_name = max_table.max_count 	0.0318650541095131
1796068	19599	list dates in months from database	select * from table group by month(datecolumn) select * from table where month(datecolumn) = 9 	9.72689708111265e-05
1806636	7221	is there a way to search 2 or more fields at the same time?	select * from (`tm_accounts`) where last_name like '%o%'     or first_name like '%o%'; 	0.000674667299555407
1819048	11174	how to store a list of users, and let the users know they are on that list	select `user`.*, `user`.`userid` as `userid_source` from   `user` where  `user`.`userid` = `user_relation`.`user_id_source` 	0
1830856	5523	prevent access from changing queries	select firstname as firstname from persons 	0.112992453593129
1839075	21053	sql query to select all columns in a table except two columns	select a, c, d, e, g, h from tablea 	0
1839171	19091	sql count, counting halfs!	select     sum(case when saleuserid = leaduserid then 1 else 0.5) from     sales where     (saleuserid = @targetid or leaduserid = @targetid) 	0.090123546247684
1841039	5202	mysql query speed issues when counting from second table	select count(*) from tickets_comment group by ticket_id where (clause matches other) 	0.240614285161204
1901337	4446	how to select many rows from a dictionary (executemany select)	select * from customers where name in ('john', 'mary', 'jane'); 	0.000583338436843718
1906361	10114	oracle number to c# decimal	select round( myfield, 18 ) from mytable 	0.0417270181231529
1921425	29653	mysql - join 2 tables with 2 id's in common	select match.*, teama.name, teamb.name from matches as match inner join teams as teama on teama.id = match.team_a_id inner join teams as teamb on teamb.id = match.team_b_id 	0.000102776992726764
1932105	2266	sqlite join query	select fi.name, fi.birthday, fi.note, fi.pic, ii.itemname, ii.price, ii.storename from friendinfo fi inner join iteminfo ii on ii.friendid = fi.friendid where fi.friendid = ? 	0.748229139169105
1934393	17092	asp.net c# search in a sql server database table	select author, title from posts where contains((author, title, postcontent), @userinput); 	0.530307929168306
1940228	39948	mysql not in or value=0?	select *  from widgets as w      left join widget-layouts as wl          on w.id = wl.widget-id  where wl.widget-id is null      or wl.position = '0' 	0.773215721873459
1942726	30221	most executed stored procedure?	select top 10         qt.text as 'sp name',        substring(qt.text, qs.statement_start_offset/2, case when (qs.statement_end_offset = -1) then len(qt.text) else (qs.statement_end_offset - qs.statement_start_offset)/2 end) as actual_query,        qs.execution_count as 'execution count',        qs.total_worker_time/qs.execution_count as 'avgworkertime',        qs.total_worker_time as 'totalworkertime',        qs.total_physical_reads as 'physicalreads',        qs.creation_time 'creationtime',        qs.execution_count/datediff(second, qs.creation_time, getdate()) as 'calls/second'   from sys.dm_exec_query_stats as qs   cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt  where qt.dbid = (select dbid                     from sys.sysdatabases                    where name = '[your database name]') order by qs.total_physical_reads desc 	0.456768968691272
1965482	7465	mysql multiple join/subquery questions	select u.user_id, u.username, u.email,  if(t1.user_id is null, 0, 1) as exists_in_table1,  if(t2.user_id is null, 0, 1) as exists_in_table2,  if(t3.user_id is null, 0, 1) as exists_in_table3 from users u left outer join table1 t1 using (user_id) left outer join table2 t2 using (user_id) left outer join table3 t3 using (user_id); 	0.256322527858538
1974205	5356	how woud i join this query in one single sql statement?	select c.name, n.country_iso_code from companies c, companies_countries x, countries n where x.company_id = c.company_id and n.country_id = x.country_id 	0.727063904766841
1996514	25546	saving data in sql server, the right approach	select  articletitle        ,articleurl from    article as a         join article_tag as x on x.articleid = a.articleid         join tag as t on t.tagid = x.tagid where   t.tagname = @sometag 	0.76818972526442
2000831	34889	compare time part of datetime data type in sql server 2005	select * from table1 where dateadd(day, -datediff(day, 0, mydatefield), mydatefield) > '12:30:50.400' 	0.0027920525740947
2003631	21743	converting blobcolumn to string in ssis script component	select left(organisationproviderid,20) as organisationproviderid from src 	0.728303679887813
2004147	41259	sql case [column] when in ('case1', 'case2') then 'oops' end?	select case when [option] in (1, 3, 99) then 'wrong option' else 'you go' end 	0.20781396863733
2014144	15301	mysql join many to many as single rows	select u.uid,        u.mail,        max(case when pf.name = 'full_name' then pv.value end) as full_name,        max(case when pf.name = 'phone' then pv.value end) as phone   from users u   left join profile_values pv on pv.uid = u.uid   join profile_fields pf on pf.fid = pv.fid                         and pf.name in ('full_name', 'phone') group by u.uid, u.mail 	0.0121210105197129
2020142	557	searching mysql by first char(s) in fields with php	select * from `tablename` where event like '1,%'; 	0.0290143574199113
2022011	21881	view all securables for roles in sql server database?	select     object_name(major_id), user_name(grantee_principal_id), permission_name from     sys.database_permissions p where     p.class = 1 and     objectproperty(major_id, 'ismsshipped') = 0 order by     object_name(major_id), user_name(grantee_principal_id), permission_name 	0.0296461373528257
2023841	8995	rotate table db2 sql	select new_column_name     from (     select col1 as new_column_name     from   table     union     select col2     from   table     union     select col3     from   table ) as new_table 	0.241081280045741
2033699	37450	top 1 with a left join	select u.id, mbg.marker_value  from dps_user u outer apply      (select top 1 m.marker_value, um.profile_id      from dps_usr_markers um (nolock)          inner join dps_markers m (nolock)               on m.marker_id= um.marker_id and                  m.marker_key = 'moneybackguaranteelength'      where um.profile_id=u.id       order by m.creation_date     ) as mbg where u.id = 'u162231993'; 	0.411756381564325
2061891	12299	how to identity the character (set-based)?	select ' _ | ||_|', 0 union all select '     |  |', 1 ... 	0.246355021328529
2066789	29641	mysql - return results grouped in a column	select a.*,         group_concat(distinct w.tag_word order by w.tag_word asc separator ',') as tags,        count(distinct w.tag_word) +        (case when `description` like '%hotel%' then 1 else 0 end) +         (case when `description` like '%london%' then 1 else 0 end) +         (case when `description` like '%lazy%' then 1 else 0 end) +         (case when `description` like '%dog%' then 1 else 0 end) +        (case when `title` like '%hotel%' then 1 else 0 end) +         (case when `title` like '%london%' then 1 else 0 end) +         (case when `title` like '%lazy%' then 1 else 0 end) +         (case when `title` like '%dog%' then 1 else 0 end) as relevance   from tbl_articles a    join tag_index i on a.article_id = i.tag_target_id    join tag_word w on i.tag_word_id = w.tag_word_id   where i.tag_type_id = 1    and w.tag_word in ('hotel', 'london', 'lazy', 'dog') group by a.article_id, a.title, a.description, a.content order by relevance desc 	0.00352520128247116
2083839	40436	how to create view that combine multiple row from 2 tables?	select   isnull(tablea.id, tableb.id) id,   isnull(tablea.date, tableb.date),   isnull(tablea.sum,0) suma,   isnull(tableb.sum, 0) sumb from   tablea full outer join tableb   on tablea.id = tableb.id and tablea.date = tableb.date order by   id 	0
2084888	26700	extract value using regular expression in mysql	select substring_index('bbb/bbbbbb/bbbbbbbbb/bbbb', '/', -1); 	0.320570382532969
2093831	2895	inserting if in a select query	select    case when sum(costo) > 0 then sum(costo)    else 0    end 'expr1' from   tdp_notaspesesezb 	0.148869063576636
2112567	11311	date of max id: sql/oracle optimization	select date from (select date from table order by id desc)  where rownum < 2 	0.0844460388708831
2128280	33754	how do i count occurrences by day in sql?	select username, count(distinct(date)) as uniquedaysappeared from occurrences group by username 	0.000512273682002828
2132018	20952	increment field in select statement	select row_number() over (order by somedata) as incfield , * from tablename 	0.0430395120603161
2135350	37964	question on converting ints to datetimes in tsql	select cast(cast(@year as varchar(4))  + right('0' + cast(@month as varchar(2)), 2) + '01' as datetime) 	0.575683477896347
2136448	33514	mysql—sum multiple counts?	select u.userrealname, u.userlevel, count(t.articleid) from user u, (     select userid, reviewsid articleid from reviews     union all     select userid, featuresid articleid from features     union all     select userid, newsid articleid from news ) t where u.userid = t.userid    and (u.userlevel = 'a' or u.userlevel = 'e' or u.userlevel ='r') group by u.userrealname, u.userlevel 	0.0595968234623888
2139396	21923	postgresql: change date by the random number of days	select date(now() + trunc(random()  * 20) * '1 day'::interval); 	0
2142392	20947	sql: how to select highest pk out of multiple records returned	select top 1        journal_entry_id, entry_date from journal_entry order by entry_date desc, journal_entry_id desc 	0
2170480	33202	joining multiple (4) tables in mysql	select employeename, positionname, groupname from employees e left join employeepositions ep on ep.employeeid = e.employeeid left join positions p on p.positionid = ep.positionid left join employeegroup eg on eg.groupid = e.groupid where e.employeeid = some_value 	0.0339471680315974
2173101	27996	mysql row subquery (multiple columns) with case (not in where-clause)	select     v1.id, v1.bekannt, v2.bekannt as lueckentext, v2.hinweis as lthinweis   from      vokabeln as v1     left outer join vokabeln as v2     on (v1.bekannt='' and v2.id = v1.hinweis)   where     v1.nutzer='test' 	0.58177279293308
2175686	12857	inserting sum of 2 tables into a row	select   (select sum(data1) from firsttable where date=@date) firsttablesum,  (select sum(data2) from secondtable where date=@date) secondtablesum 	0
2186682	40119	access - merge two databases with identical structure	select t.id, t.field1, t.field2 into newtable from (select a.id, a.field1, a.field2 from table1 a union select x.id, x.field1, x.field2 from table1 x in 'c:\docs\db2.mdb' where x.id not in (select id from table1)) t 	0.01517310881799
2186985	28643	using a right outer join to match records from two different databases	select *  from assetcomptype_equipmentproperty_linktable t1   right outer join      [database a].dbo.assetcomptype_equipmentproperty_linktable t2         on t1.assetcomptypeid = t2.assetcomptypeid 	0.00401867803851272
2196399	31296	mysql find the total amount of posts per user	select users.*, count( posts.user_id )  from posts left join users on users.id=posts.user_id  group by posts.user_id 	0
2201170	33837	how to select multiple rows filled with constants?	select 1, 2, 3 union all select 4, 5, 6 union all select 7, 8, 9 	0.0412344094226958
2208701	36963	getting parental status from a self-referencing table	select  i.item_id,         item_id in         (         select  item_parent         from    items         ) from    items i 	0.00137080413464703
2214222	36511	the insert statement conflicted with the foreign key constraint "fk_usercars_aspnet_users"	select * from aspnet_users where useridguid = @theguidbeinginserted 	0.00205515991909217
2223696	40684	sql server join - displaying two joined values in one query that map to one other table?	select      submitted.[user name] as [submitted user],      assigned.[user name] as [assigned user]  from items      left join users submitted on items.[submitted user] = submitted.[user id]     left join users assigned on items.[assigned user] = assigned.[user id] where items.[item id] = '234' 	0
2239117	11425	mysql - select statement, order by number of comments per article	select      tbl_article.*, count(tbl_comments.article_id) as total_comments from      tbl_article left join      tbl_comments on tbl_comments.article_id = tbl_article.id group by      tbl_article.id order by      count(tbl_comments.article_id) 	0.000168697281917993
2249166	30367	sql - how to insert results of stored_proc into a new table without specifying columns of new table?	select * into #temp  from openrowset (     'sqloledb'   , 'server=(local);trusted_connection=yes;'   , 'set fmtonly off exec database.schema.procname'   ) a 	0
2257275	25581	postgres: timestamp bigger than now	select * from tablename where mytimestamprow >= now() 	0.0168181951792314
2260619	12167	mysql inner join single query	select `u1`.`name` `name1`, `u2`.`name` `name2`       from `friends` `f` inner join `users` `u1`         on `f`.`id1` = `u1`.`id` inner join `users` `u2`         on `f`.`id2` = `u2`.`id` 	0.73658473839265
2267526	26066	sql server: how to calculate different sums in a single query	select  salesman, sum(amount), sum(case when accessory = 1 then amount else 0 end) from    salestable t join    salesorder o on      o.salesorder = t.salesorder group by         salesman 	0.00121008695387575
2294505	25391	only one expression can be specified in the select list when the subquery is not introduced with exists	select  issueno,          kendracode,          issuetime,          dateofissue,          p_motabags,          p_motaweight,          p_patlabags,          p_patlaweight,          p_sarnabags,          p_sarnaweight,          newbags,         oldbags,          transportername,          trucknumber,          drivername,          truckowner,         societycode,          rfs.* from    issuetosangrahankendra_soc s left join         (   select  paddymotaw,                      paddypatlaw,                      paddysarnaw,                      bagsmota,                      bagspatla,                      bagssarna,                     pc_id,                      sangrahankendraid,                      societycode,                     dm_id              from    receivefromsociety          ) rfs on rfs.dm_id =s.issueno where   kendracode='4403'  order by    societycode 	0.698205986774604
2298202	15633	sql - how to count groups of rows and display the top/bottom 3	select top 3 item_id, count(*) as itemcount  from table  group by item_id order by itemcount 	0
2309227	30738	sqlite select with condition on date	select dateofbirth from customer where dateofbirth  between date('1004-01-01') and date('1980-12-31');   select dateofbirth from customer where date(dateofbirth)>date('1980-12-01'); select * from customer where date(dateofbirth) < date('now','-30 years'); 	0.0730160566161458
2340864	22087	get last value based on an id in sql server 2005	select top 1 empid, remainingbalance  from salary where empid = '15' order by somedatetimefield desc 	0
2341659	10405	problem joining tables where joined table needs to be ordered before grouping	select t.threadid, p.postid, p.posted from thread t inner join (     select threadid, max(posted) as maxposted     from post     group by threadid        ) pm on t. threadid = pm.threadid inner join post p on pm.threadid = p.threadid and pm.maxposted = p.posted order by p.posted desc 	0.0426188801246363
2353428	12611	coalescing rows based on field value in row	select      t1.year_end,     t1.entity_type,     t1.ratetype,     coalesce(t2.taxrate, t1.taxrate)   from     rates as t1 left join     rates as t2 on         t1.year_end = t2.year_end         and t2.entitytype is null where t1.year_end = @year     and t1.entitytype = @entitytype 	0
2366962	4098	pl/sql: find the server name for an oracle database	select  host_name from    v$instance 	0.0356203370321068
2374778	11865	how do i combine these sql select queries into one select statement	select sum( incidents ) , neighborhoods,  'adw' as offense  from ( select *  from `adw_2009_incident_location`  union all select *  from `adw_2008_incident_location` union all select *  from `adw_2007_incident_location` union all select *  from `adw_2006_incident_location` ) as combo  group by neighborhoods   union all select sum( incidents ), neighborhoods,  'fire' as offense  from ( select *  from `fire_2009_incident_location`  union all select *  from `fire_2008_incident_location` union all select *  from `fire_2007_incident_location` union all select *  from `fire_2006_incident_location` ) as combo2 group by neighborhoods 	0.00999736108724464
2378606	32885	oracle timestamp: extract full hour	select  trunc(m.begin, 'hh24') from    mytable m 	0.0072387324763517
2385812	28458	how to store the mysql query result into a local csv file?	select a,b,c from table_name into outfile '/tmp/file.csv' fields terminated by ',' enclosed by '"' lines terminated by '\n' 	0.0115196833478856
2394359	24334	if using raw activerecord::base.connection(), how obtain last inserted primary key value?	select last_insert_id() 	0
2414805	27141	getting a count of each product for each id	select id         , sum( case when product = 'bpl' then 1 else 0 end ) as bpl         , sum( case when product = 'sony' then 1 else 0 end ) as sony         , sum( case when product = 'lg' then 1 else 0 end ) as lg         , sum( case when product = 'samsung' then 1 else 0 end ) as samsung from table group by id 	0
2427255	4559	how to select multiple rows by primary key in mysql?	select * from table where primary_key in (value1, value2, ...) 	0.000810121448760225
2434472	30931	sql: getting the full record with the highest count	select * from data inner join (select idnum, max(count) from data             group by idnum )sub on sub.idnum=data.idnum && sub.count=data.count 	0.000257160664760943
2436274	36735	sort mysql query by filtered query	select  *  from    content  order by case              when threadname like '%$filter%' then 0             else 1         end asc,         lastupdated desc 	0.415431689184666
2440412	14850	mysql select two prior to and one after now()	select * from    (             select *             from table             where event_time < now()             order by event_time desc             limit 2         ) first2 union all select * from    (             select *             from table             where event_time > now()             order by event_time asc             limit 1         ) next1 order by event_time 	0.000525980201020604
2450810	30930	how do i put several select statements into different columns	select     count(user_id) as '20100101'    ,null as '20100102'    ,null as '20100103'    ,null as '20100104'    ,null as '20100105'   from     event_log_facts   where     date_dim_id=20100101   union   select     null as '20100101'    ,count(user_id) as '20100102'    ,null as '20100103'    ,null as '20100104'    ,null as '20100105'   from      event_log_facts   where     date_dim_id=20100102   union   select     null as '20100101'    ,null as '20100102'    ,count(user_id) as '20100103'    ,null as '20100104'    ,null as '20100105'   from     event_log_facts   where     date_dim_id=20100103 	0.000201456208777631
2466085	16028	query not returning rows in a table that don't have corresponding values in another [associative] table	select a.id, a.content, w.name  from articles a left join articles_to_writers atw on a.id = atw.article_id     left join writers w on w.id=atw.writer_id where a.content like '%the%' 	0
2471546	16708	mysql: getting "busiest" or "most popular" hour from a datetime field?	select hour(date_created) as h  from my_table  group by h  order by count(*) desc  limit 1 	0
2480713	34158	mysql: averaging with nulls	select avg(coalesce(col1, 0) + coalesce(col2, 0)), count(col3) from table1 where coalesce(col1, col2) is not null  group by somearbitrarycol having avg(coalesce(col1, 0) + coalesce(col2, 0)) < 500 and count(col3) > 3 order by avg(coalesce(col1, 0) + coalesce(col2, 0)) asc; 	0.387020148188183
2490839	20794	how can i make an sql statement that finds unassociated records?	select countryid, countrycode    from tblcountry    where countryid not in ( select countryid from tblprojectcountry ) 	0.12534601812196
2506431	32780	mysql, if a value is in one of two columns, return the value from the other one	select user1 from tab where user2=id union all select user2 from tab where user1=id 	0
2508615	4986	how to get only the date from the sql server	select book_id, bookname,author,bookprice  from book inner join favcategory on book.category_id = favcategory.category_id  where favcategory.user_id = " + useridlabel.text + "  and convert(nvarchar, orderdate, 111) = convert(nvarchar, getdate(), 111) 	0
2508689	37792	make a set from csv values in tsql	select * into #temp from dbo.udf_list2table( 'a,b,c', ',')  select * from #temp where item not in (select id from mytable) 	0.00661242742449254
2512272	40741	mysql: count rows by field	select type, count(type) from tbl_table group by type; 	0.00545038270594392
2516546	25102	select count / duplicates	select city, count(city) as thecount from (select city, state from tblcitystatezips group by city, state) as c group by city having count count(city) > 1 	0.0799143473291847
2519879	22946	sql server - compare int values in a select clause	select case when @a = @b then 1 else 0 end 	0.0553097072121744
2526430	8913	sql: select random row from table where the id of the row isn't in another table?	select top 1 * from urls where (select count(*) from urlinfo where urlid = urls.urlid) = 0  order by newid() 	0
2537707	19865	get more records that appear more than once	select  distinct l.* from    @table l join      @table r on  convert(varchar, l.[date], 102) = convert(varchar, r.[date],102) and l.id != r.id 	0
2547752	8517	sql: need to sum on results that meet a having statement	select sum(spent) from (    select sum(money_spent) as spent    from moneytable    where (date >= '2010-01-01')    group by userid    having (sum(money_spent_on_candy)/sum(money_spent)) > 0.1 ); 	0.139325132869435
2549313	33583	how to reference a sql server with a backslash (\) in its name?	select top 1 *   from [devserverb\2k5].master.sys.tables 	0.132013974778091
2551298	35262	datatable identity column not set after dataadapter.update/refresh on table with "instead of"-trigger (sqlserver 2005)	select @@identity 	0.0327308723312969
2558825	11202	how to detect if a string contains atleast a number?	select * from table where column like '%[0-9]%' 	0.00852489773679302
2580426	10480	query to look up comment in one table, username in another table	select comment.comment, comment.datecommented, login.username from comment left join login on comment.loginid=login.loginid where submissionid=$submissionid order by comment.datecommented desc  limit 100"; 	0.00132888784010849
2601930	5468	max count with joins	select    u.login, t1.total_sess, t1.total_min, t2.mf, t2.sess_mf, t2.min_mf from      users u left join (   select   userid, count(minutes) as total_sess, sum(minutes) as total_min   from     sessions   group by userid ) as t1 on t1.userid = u.id left join (   select   userid, name as mf, count(*) as sess_mf, sum(minutes) as min_mf   from     sessions s   join     computers c on c.id = s.computerid   group by userid, computerid   having   count(computerid) >= all(select   count(*)                                     from     sessions s2                                     where    s2.userid = s.userid                                     group by s2.computerid) ) as t2 on t2.userid = u.id 	0.465425028286635
2609424	12925	asp, sorting database with conditions using multiple columns	select * from projects order by iif(complete = 'yes', enddate, startdate) 	0.0779242714710624
2659555	12195	getting two items from same table in select statment	select sport_activity_id, t1.team_name, t2.team_name, date, time  from sportactivity join teams t1 on home_team_fk = t1.team_id join teams t2 on away_team_fk = t2.team_id where competition_id_fk = 2 	0
2683911	20973	how to retrieve distinct values from multiple columns	select     itemvalue,     count(*) from (     select         column1 itemvalue     from         datatable     union all     select         column2 itemvalue     from         datatable     union all     select         column3 itemvalue     from         datatable     union all     select         column4 itemvalue     from         datatable ) uniondatatable 	0
2684844	33166	two query in one with sql server	select t1.[idclient] from   [table] t1 where  [entite] is null         and not exists (            select null            from   [table] t2            where  t2.[entite]=t1.[idclient]        ) 	0.0753345117590792
2688153	9401	database design mysql using foreign keys	select  * from    stocks s inner join         stock_tags st on s.id = st.stock_id inner join         tags t on st.tag_id = t.id etc... 	0.0212093580132722
2697478	38252	count total records after groupby select	select <your_complicated_query>; select found_rows(); 	0.00062892336064797
2703288	22108	how to efficiently select rows from database table based on selected set of values	select * from trans_table where code in (?,?,?,?,?,?,?,?,?,?,?) 	0
2708557	37133	how to determine the difference among dates in the same column?	select     t.id,     t.name,     t.birth,     abs(datediff(t.birth,t2.birth)) as diff  from table t inner join table t2 on (t.id+1) = t2.id order by abs(datediff(t.birth,t2.birth)) desc 	0
2716166	6297	do views only perform the joins that they need to, or all joins always?	select a.val, b.val, c.val from a join b on a.id = b.id join c on a.id = c.id 	0.0978192933544566
2720088	13810	aggregate keeping the row with the max value	select user_id, max(score) from user_scores group by user_id order by max(score) 	0.00233138271674185
2726052	1194	select the latest record for each category linked available on an object	select * from tblmachinereports t where logdate = (select max(logdate) from tblmachinereports t2 where t.machineid = t2.machineid and t.category = t2.category) 	0
2727276	37831	selecting random top 3 listings per shop for a range of active advertising shops	select  user_id         , listing_id from    (           select  l.user_id                    , l.listing_id                   , rownumber = row_number() over (partition by l.user_id order by newid())           from    listings l                   inner join (                     select  user_id                     from    listings                     group by                             user_id                     having  count(*) >= 3                   ) cnt on cnt.user_id = l.user_id           ) l  where   l.rownumber <= 3 	0
2739903	28182	sql query to get most	select top 1     skillid, s.description,count(skillid) as countof     from employeeskills   e         inner join skills s on e.skillid=s.skillid     group by skillid, s.description     order by 3 desc 	0.0102150338614915
2761446	6689	how to select a limited amount of rows for each foreign key? (and how to specify the relatioship)	select x . * from ( select t . * , f.categoria_id as idcategoria, case when @cat != f.categoria_id then @rownum :=1 else @rownum := @rownum +1 end as rank, @cat := f.categoria_id as catteste from feed_entries t, feeds f join ( select @rownum := null , @cat :=0 )r where t.feed_id = f.id order by f.categoria_id desc )x where x.rank <=3 and x.deleted =0 order by x.categoria_id, x.date desc limit 50 	0
2771270	31220	date range intersection in sql	select sum( least(@range_end, stop) - greatest(@range_start, start) ) from table where @range_start < stop and @range_end > start 	0.0113635844451836
2776225	25665	sql server: position based on marks	select     studentid,     studentname,     marks,     rank() over (order by marks desc) as position from student 	0.0133188124170507
2791352	38794	complex query with two tables and multilpe data and price ranges	select * from properties as p where exists                (select * from properties_prices as pp1        where p.id = pp1.property_id and             pp1.price_per_day between 10 and 100 and             (pp1.date_begin <= "2010-12-31" or pp1.date_end >= "2010-05-01")) and       not exists            (select * from properties_prices as pp2        where p.id = pp2.property_id and             pp2.price_per_day not between 10 and 100 and             (pp2.date_begin <= "2010-12-31" or pp2.date_end >= "2010-05-01")) order by name   limit 10 	0.00367058430310456
2800534	3765	order result in sqlite	select     *,     case when `word` = 'sim' then 1          when `word` like 'sim%' then 2          when `word` like '%sim' then 4          else 3     end `sort` from `dblist` where `word` like '%sim%' order by `sort` , `word` 	0.31168873039894
2814244	34310	best way to sort-n-concatenate 5 columns	select ...     , stuff(             (             select ' ' + z.col             from    (                     select pkcol, a as col from table                     union all select pkcol, b from table                     union all select pkcol, c from table                     union all select pkcol, d from table                     union all select pkcol, e from table                     ) as z             where z.pkcol = table.pkcol             order by col             for xml path('')             ), 1, 1, '') as combined from table 	0.0102598332170156
2817078	12948	oracle: how can i get all the triggers linked to a specific table?	select * from user_triggers where table_name = 'name_of_your_table'; 	6.5772011334761e-05
2819616	24744	how to count two fields by using select statement in sql server 2005?	select     sum(case col1 when 1 then 1 else 0 end) as count1,     sum(case col1 when 0 then 1 else 0 end) as count0 from table1 	0.0967791254392633
2824147	6593	how to get list of databases that a user owns?	select datname from pg_database join pg_authid on pg_database.datdba = pg_authid.oid where rolname = 'novicedba' 	9.77859014524131e-05
2828572	37135	sql - sub count	select adviceno,        registration,        rank () over (partition by adviceno order by registration asc) my_rank   from tblsalesdetail; 	0.537208047429464
2833294	13598	select table name that is inside union	select f1,f2, xxx from  (select     *, 'tbl1' as xxx from         tbl1 union all select     *, 'tbl2' as xxx from         tbl2) 	0.104604365188271
2840310	32216	how do i select top ranker by date in mysql	select id, rank, something  from person  where date = date(now())  order by rank desc limit 1; 	0.0118025407135144
2852529	37936	sql server 2008 - conditional range	select   * from   mytemptable t where   (t.averagerating >= @lowestrating and    t.averagerating <= @highestrating)   or t.totalreviews = 0 	0.56652837775194
2854985	12790	what is the best way to use number format in a mysql query?	select     format(field, 2) as formatted from     table 	0.283188832545984
2865514	23434	query to get 3rd largest amount and 2nd largest amount from table	select ... from ... order by column desc limit 2 offset 1; 	0
2866519	14646	mysql look for missing ratings	select * from portfolio left join (   select portfolioid from rating where email = "test@test.com" ) as rated using (portfolioid) where rated.portfolioid is null 	0.304730741255419
2868102	28767	create table by copying structure of existing table	select * into drop_centers_detail from centers_detail where 1 = 0 	0.00335220825624332
2874838	20904	sql script to generate a database dictionary **with linked fields**	select c.table_schema, c.table_name, c.column_name, c.data_type     , pkcol.table_schema, pkcol.table_name, pkcol.column_name from information_schema.columns as c     left join (information_schema.constraint_column_usage as fkcol         join information_schema.referential_constraints as fk             on fk.constraint_name = fkcol.constraint_name         join information_schema.constraint_column_usage as pkcol             on pkcol.constraint_name = fk.unique_constraint_name)         on fkcol.table_schema = c.table_schema             and fkcol.table_name = c.table_name             and fkcol.column_name = c.column_name 	0.0882344828646149
2886189	34770	converting an int to an ip address	select '0.0.0.0'::inet + 16909060 	0.306208594741388
2895751	12831	do i need to drop index on temp table?	select object_name(object_id), * from tempdb.sys.indexes 	0.319537569661318
2901205	9261	sql server add primary key	select * into backup_ orders from orders 	0.0375850020321657
2907671	39669	extract data from two tables and order by date	select id, news, date_added,"" as extra from table1 union all select id, news, date_added,extra from table1 order by date_added 	5.87409243121801e-05
2952559	21519	how to show previous day values in query	select     date, no, turnover, [total win], [games played], [credit in], [bill in], [hand pay] 	0
2958046	37503	mysql specifying exact order with where `id` in (...)	select * from articles where articles.id in (4, 2, 5, 9, 3) order by find_in_set(articles.id, '4,2,5,9,3') 	0.386528402113327
2965174	27285	union on the same table	select * from mytable where id2 in (select id2 from mytable group by id2 having count(*)>=2) and (id1=196 or id1=150) 	0.0040117391690625
2966438	14503	displaying records up to a certain 'age' - mysql query syntax?	select * from table where datecolumn > date_sub(now(), interval 4 month) 	0.00229619809160194
2972142	23776	how i can get log from database in oracle?	select object_name, last_ddl_time from dba_objects order by last_ddl_time desc; 	0.00999416025085953
2983483	23590	create table from another table in different database in sql server 2005	select *  into temp2.dbo.b from temp.dbo.a 	0.000143341028578636
2992449	18447	average of a sum in mysql query	select cashier,        sum(sales_x0020_value) / count(distinct transaction_x0020_number) as 'avg' from products  where date = {d'2010-06-04'} group by cashier 	0.00495022342515673
3002132	10483	using like in mysql select fields	select case when `my_column` like '%thepattern%'         then 'did_match' else 'no_match' end case as mytest   from ... 	0.412594429518912
3010906	28860	how to identify what locked pl/sql package (oracle 10.0.4.2)?	select * from v$locked_object lo join dba_objects o on lo.object_id = o.object_id where o.object_name = 'xxpackage namexx' and o.object_type = 'package'; 	0.722011804417465
3011456	26783	how do you get average of sums in sql (multi-level aggregation)?	select rdate,rtime,avg(rsum) as ravgsum from (     select rdate,rtime,rid, sum(rval) as rsum     from xx     where rdate = '2010-01-01'     group by rdate,rtime,rid ) as subq group by rdate,rtime 	0.00165831833758925
3032383	28424	active user tracking, php sessions	select count(*) from active where timestamp > unix_timestamp() - 1800      and nick not like '%[afk]%' 	0.0566272571733788
3038575	28666	distinct clause in sqlite	select min(t.a) as a,          t.b     from table t group by t.b 	0.587711476822369
3053003	13714	filter rows on the basis of "first name" + "last name" in sql	select * from @test where (fname like '%' + @searchkeyword + '%') or (lname like '%' + @searchkeyword + '%') or (fname + ' ' + lname like '%' + @searchkeyword + '%') 	0
3062391	25323	ip address numbers in mysql subquery	select  event.id, event.event_name, get_provider_name(event.ip_address) as provider from events 	0.100046973862072
3090048	8880	prevent repeated row from returning in mysql	select distinct restaurant.name, restaurant.place from restaurant, type_stack where restaurant.id = type_stack.rest_id and type_stack.type = '0' and type_stack.type = '1' and type_stack.type = '2' limit 0 , 30 	0.00714913227236597
3096866	8069	sql server - need a sql query to identify/highlight specific changes in an audit table	select invoiceid,salesperson,auditdate from myaudittable where invoiceid in   (select distinct a.invoiceid   from myaudittable a inner join myaudittable b on a.invoiceid = b.invoiceid and           a.salesperson <> b.salesperson)                  group by invoiceid,salesperson 	0.180618933423372
3097321	3381	mysql: group by id, get highest priority per each id	select a.id, a.vehicle_id, a.filename, a.priority from pics a left join pics b                on b.vehicle_id = a.vehicle_id  and b.priority > a.priority left join pics c                on c.vehicle_id = a.vehicle_id  and c.priority = a.priority  and c.id < a.id where b.id is null and c.id is null 	0
3106317	31135	return query results into an array	select     plr_function(       array_agg(array[s.id,s.latitude_decimal,s.longitude_decimal])     )   from     climate.station s   where     s.applicable and     s.latitude_decimal between box.latitude_min and box.latitude_max and     s.longitude_decimal between box.longitude_min and box.longitude_max 	0.0276574673294464
3113901	3110	creating a custom forum, help with building a query that counts posts in a categories etc	select c.forum_cat_id,        count(p.fk_forum_cat_id),        max(p.date_added),        (select p2.post_title            from forum_post as p2             where p2.forum_cat_id = c.forum_cat_id            order by date_added desc            limit 1)     from forum_cat as c inner join                 forum_post as p on p.fk_forum_cat_id = c.forum_cat_id     group by c.forum_cat_id; 	0.708371719234597
3118352	37126	postgresql count() and arrays	select sum(array_length(episode_number, 1))   from episodes  where show_id = 1 	0.106133212404886
3120083	15933	how do i join two mysql tables using a function	select t.type, t.latitude, t.longitude, s.neighborhood    from my_type_table t, neighborhood_shapes s where mywithin(pointfromtext( concat( 'point(', t.latitude, ' ', t.longitude, ')' ) ) ,               s.neighborhood_shapes.neighborhood_polygons ) = 1 	0.280793902677596
3123651	8348	sql: splitting a column into multiple words to search user input	select word, count(word) * 10 as wordcount from sourcetable inner join searchwords on charindex(searchwords.word, sourcetable.name) > 0 group by word 	0.000980062000234562
3130574	12719	any tools to export the whole oracle db as sql scripts	select dbms_metadata.get_ddl('table',table_name) from user_tables; 	0.605918426246263
3131454	35108	displaying data from multiple tables	select        pname as productname ,       productcode as pc       quantity as salesqty ,             (select                     quantity               from breakages              where breakages.productcode = pc              ) as breakqty ,              (select                      quantity               from salesreturn              where productcode = pc) as returnqty        from saleslog; 	0.00271312187302546
3143384	6121	sql select count(person_id) > 3 from	select t.person_id     from table t group by t.personid   having count(t.personid) > 3 	0.0274886551962142
3148408	14436	how to use concatenation '||' with distinct clause of select query?	select  distinct 'label1:' || col1 from tab1 order by 1; 	0.671103028694148
3148465	31693	mysql pagination with multiple tables	select  o.*, m.* from    (         select  *         from    organizations         order by                 id         limit 10         ) o left join         organizationmeta m on      m.orgid = o.id 	0.381383139781316
3153916	9914	converting sql to access	select     sum(iif([column2] = 'cylinder', 1, 0)) as 'cylinder count',     sum(iif([column2] = 'snap', 1, 0)) as 'snap count',     sum(iif([column2] = 'tip', 1, 0)) as 'tip count',     sum(iif([column2] = 'other', 1, 0)) as 'other count' from [tablename] where [column1] = '1.9 qns-quantity not sufficient' 	0.781217885860223
3191856	25579	sql wildcard matching excluding a specific pattern	select id, name from tblusers where name like 'j%n'  and name not like 'john' 	0.0137694785375782
3193384	40292	display sql custom text from table column result	select    case      when score >= 40 then 'very agreed'     when score >= 20 then 'agree'     else 'strongly not agree'   end from table1 	0.00068031408226176
3196012	7663	mysql result not returned if count 0	select      levels.id,     levels.name,     count(pages.id) as pagecount from levels left join page_levels     on levels.id = page_levels.level_id left join wp_pages as pages     on page_levels.page_id = pages.id and pages.status = 'open' group by levels.id 	0.163375308640688
3197626	12071	concatenate multiple rows	select custid      , (select ca.actionid [@value]              , actionname [text()]           from dbo.custaction ca          inner join dbo.action on ca.actionid = action.actionid          where ca.custid = c.custid            for xml path('option'), type) availableaction   from dbo.cust c 	0.00201698440891795
3197929	11932	sql sort/cast last five chars question	select   col, case left(right(col, 5), 1) when '-' then 0 else 1 end as old from   table order by   old, col 	0.0543071024772931
3226912	34943	join three tables	select a.* from tablea a left outer join tableb b on (a.id = b.a_id) left outer join tablec c on (a.id = c.a_id) where b.a_id is not null    or c.a_id is not null 	0.183360534970273
3227986	28067	how do i efficiently inverse a many-to-many sql query?	select m.* from m   where not exists  (select * from manytomanytable mmt            where mmt.m = m.id and n=@id ) 	0.645608056884822
3240710	8016	get us, uk in one table, cn and jp in the other, but not br in both	select cl.countrycode,        cl.language   from countrylanguage cl  where not exists(select null                     from countryname cn                    where cn.countrycode = cl.countrycode) union all select cn.countrycode,        cn.name   from countryname cn  where not exists(select null                     from countrylanguage cl                    where cl.countrycode = cn.countrycode) 	0.000403453748200156
3241339	5505	how to add 2 temporary tables together	select id, sum(score) as score from (   select id, score from t1   union all   select id, score from t2 ) t3 group by id 	0.00430081380925083
3247630	5796	mysql group by age range including null ranges	select     sum(if(age < 20,1,0) as 'under 20',     sum(if(age between 20 and 29,1,0) as '20 - 29',     sum(if(age between 30 and 39,1,0) as '30 - 39', ...etc. from inquiries; 	0.000347081672075244
3261789	19469	mysql: select if next row is not as what is expected	select line2.*    from log line2         join log line1         on line2.id = line1.id + 1   where line1.function = 'done()'     and line2.function = 'check()' 	0.71695453187971
3263148	24414	sql server - select integer that falls between brackets ( )	select substring(fld, patindex('%([0-9]%)', fld) + 1, len(fld) - case patindex('%([0-9]%)', fld) when 0 then 0 else patindex('%([0-9]%)', fld) + 1 end) 	0.198853259615002
3263820	23793	sql server query	select     keyword, d1, d2, d3, d1 + d2 + d3 as total from     mytable 	0.698580681859737
3266360	37892	database joins with three tables, one is a category / tag table	select distinct u.name from unit u  join unitcategory uc on u.id = uc.unitid join unitcategoryuser ucu on uc.category_id = ucu.categoryid where ucu.userid = youruserid union select distinct u2.name from unit u2 join unitcategoryuser ucu2 on u2.id = ucu2.unitid where ucu2.userid = youruserid 	0.00129235965894859
3270545	15355	get the rows, where day is equal to some value	select <columns> from <table> where dayofmonth(<the-date-column>) = 1 	0
3274434	34029	how to treat a string as a month in sql server	select charindex(substing(joining_month,1,3),'xxjanfebmaraprmayjunjulaugsepoctnovdec')/3             as monthnumber, *              from table1              where monthnumber >or< 3 	0.00543973867479427
3290636	11165	how to truncate the text returned for a column in a mysql query	select id, substring(full_name,1, 32), age from user 	0.00545994681339471
3301758	24998	oracle: how do i grab a default value when a more specific value is null from within the same query?	select   nvl(     (select val from k_v where user_id = 123 and k = 'favorite_color'),     (select val from k_v where user_id = 0 and k = 'favorite_color')   ) val  from dual ; 	0
3305709	9145	postgres, table1 left join table2 with only 1 row per id in table1	select distinct on (user_id) * from user_stats order by datestamp desc; 	0
3306605	13127	oracle join v$sqlarea v$session	select s.sid, s.serial#, a.sql_text from v$session s join v$sqlarea a on a.hash_value = s.sql_hash_value; 	0.681931842834105
3310562	4290	mysql: how to "sum" product weight if the product are in different lines	select sum(weight_kg * quantity) as weight from table where product_id like '2%' 	0
3318726	30980	how to select entries from this relationship?	select *  from `feed_entries` where id in (     select e.id     from `feed_entries` as `e`      inner join `feeds` as `f` on e.feed_id =f.id      inner join `entries_categorias` as `ec`      on ec.entry_id =e.id inner join `categorias` as `c`      on ec.categoria_id =c.id      where c.nome in ('google','apple')      and (e.deleted =0)     group by e.id     having count(distinct ec.id) = 2 ) 	0.00232960987164911
3359374	11369	how to return different strings from a boolean type in mysql?	select case when bool_value <> 0 then "yes" else "no" end 	0.00107698107658621
3360205	33897	select distinct items rows and associated columns based on a condition	select itemid, count   from   ( select date, itemid, count, rank() over (partition by itemid, order by itemid, date desc) r     from table   )    where r = 1 	0
3361185	40432	problem with adding foreign key to table in mysql	select * from potovanja p where not exists     (select * from users where users.username = p.username) 	0.0253314133855105
3365697	14748	add empty row to query results if no results found	select     id, category from mytable where category = @category union all  select     0, '' where not exists (select * from mytable where category = @category) 	0.00250605150528307
3376458	21363	php mysql sort by date (newest)	select * from articles order by time desc 	0.00524484320928315
3381101	37453	mysql query to get list of latest updated pages, but only one result for every slug?	select * from pages p1 left join pages p2 on p1.slug = p2.slug and p1.updated < p2.updated where p2.updated is null order by p1.updated desc 	0
3402374	16962	mysql subquery in single table	select   e.id from    entries e where    e.date = curdate() and    e.id not in      (select id from entries e2 where e2.date < e.date) 	0.10697405415718
3406820	1839	join that doesn't exclude all records if one side is null	select * from orders o     inner join ordersrows r on r.idorder = o.idorder     left join ordersrowsoptions ro on ro.idorderrow = r.idorderrow  where  r.idproduct = [foo] 	0.0004821100603692
3414804	19715	how can i customize date format	select     *  from     yourtable  where     rtrim(convert(char(19), setdate, 101)) = '3/12/2010' 	0.10635643700725
3417169	4988	sql query converting rows to columns	select x.orderid,        stuff(isnull((select ', ' + y.productid                                   from order_details y                       where y.orderid = x.orderid                    group by y.productid                     for xml path ('')), ''), 1, 2, ''),        x.total_items   from (select od.orderid,                sum(od.quantity) as total_items           from order_details od       group by od.orderid) x 	0.025115763392645
3426310	29150	calculations in mysql statement for rating	select *, (((9/rateup+ratedown)*rateup)+1) as ord from table where published = 1 order by ord desc 	0.487482264992128
3427456	12806	datetime implementation in php mysql	select time(fieldname) from tablename 	0.778618626584352
3434437	31747	what's the most efficient way to check if a record exists in oracle?	select case              when exists (select 1                           from sales                           where sales_type = 'accessories')              then 'y'              else 'n'          end as rec_exists from dual; 	0.00517046987627232
3439624	4503	sqlite timestamp formatting	select strftime('%d - %m  - %y ', datetime(1281353727, 'unixepoch')) from visits; 	0.38432546249662
3458863	39867	sql to combine 2 tables	select names.id, names.f_name, names.l_name, prices.item_name, prices.item_price from names  left outer join prices    on names.id = prices.id 	0.0101635049742992
3459306	37370	sql statement to access data across relationships	select publicationid from authorsjointable a join publications p      on (p.id = a.publicationid) order by p.year desc 	0.311417632756887
3468939	16384	sql and on column from join table	select cpn, status, title, value_category, rating_category, parts.id from `parts` inner join     (        select distinct part_id from `vender_parts` join on (`vendors`.`id` = `vendor_parts`.`vendor_id`)        where concat(ifnull(`vendors`.`name`,''),ifnull(`vendors`.`abbreviated_name`,'')) like '%vendor1%'    ) `vender1` on `vender1`.`part_id` = `parts`.`id` inner join     (        select distinct part_id from `vender_parts` join on (`vendors`.`id` = `vendor_parts`.`vendor_id`)        where concat(ifnull(`vendors`.`name`,''),ifnull(`vendors`.`abbreviated_name`,'')) like '%vendor2%'    ) `vender2` on `vender2`.`part_id` = `parts`.`id` group by cpn 	0.00780523749654746
3471041	6380	mysql: select occurences of a row, then combine results with another query	select * from (     select like_song_id, count(like_song_id) as occurrences     from likes     group by like_song_id     order by occurrences desc     limit 100 ) t1 join songs on songs.song_id = t1.like_song id join likes on likes.like_song_id = t1.like_song id and userid = 123 	0
3472207	37394	mysql query aggregating users who perform an activity	select number_of_activities, count(*) as cnt from (    select count(*) as number_of_activities    from ca_activity    group by user_id ) t1 group by number_of_activities order by number_of_activities 	0.153292917391537
3479766	34532	how to find repeated rows?	select col1, col2,..collast, count(*) as numdups from yourtable group by col1,col2,...,collast having count(*) > 1; 	0.00180339244639051
3486413	28652	how can i combine these three queries?	select     ( ( select          sum(a.a)     from          a join b          on a.bid = b.id      where          b.userid = user.id ) +      ( select            sum(c.c)       from            d left join (c)            on (d.id = c.did)      where d.userid = user.id ) +     ( select           sum(e.e)       from            e        where            e.userid = user.id ) ) from     user 	0.112922686363
3490731	35980	sql - how to join top ordered results from pictures table with product table?	select p.id,        p.name,        p.model,        x.url    from products p    join pictures x on x.pid = p.id   join (select t.pid,                max(t.order) as max_order           from pictures t       group by t.pid) y on y.pid = x.pid                        and y.max_order = x.order 	0.000237625239451072
3495446	16953	how do i find a disabled index on sql server 2008	select     sys.objects.name,     sys.indexes.name from sys.indexes     inner join sys.objects on sys.objects.object_id = sys.indexes.object_id where sys.indexes.is_disabled = 1 order by     sys.objects.name,     sys.indexes.name 	0.239160808844464
3496636	35928	using phpmyadmin to manage duplicates	select t1.id, t2.id, t1.value from table t1 inner join table t2 on t1.value=t2.value where t1.id < t2.id 	0.705241437889598
3498256	19083	physical database and log file location	select * from sys.database_files 	0.118591269940592
3504397	3435	want to sum some fields and leave others alone sql	select region,      case when repeatlength >= 18 then ">=18" else repeatlength end as repeatlength,      count(*) as count   from alignedrepeats  group by region,      case when repeatlength >= 18 then ">=18" else repeatlength end; 	0.0359556581757927
3510982	10104	t-sql: how to return 0 rows in from stored procedure, and how to use xact_abort and try/catch	select top 0 null as myvalue 	0.0107472505036393
3515351	5875	join in the same table?	select * from show_detail where ch_id="0140.zee.in" and (`date_column` between `2010-08-17` and `2010-08-18`') 	0.0109533030933347
3516064	19040	creating a sql table from a comma concatenated list	select * into #ids from dbo.split(',', @idlist) select t.* from table1 t  join #ids i     on t.id = i.s 	0.000235343509326371
3517433	837	mysql - how to select users who have similar info (like a shared phone number)	select ... from users u1 join users u2  on u1.user_id <> u2.user_id and u1.phone_number = u2.phone_number; 	0
3523144	32580	sql count across 3 tables	select  c.categoryid      , c.categoryname      , isnull(count(cc.charityid), 0) as charitycount      , c.isdeleted  from    charity.categories c  left join charity.charitycategories cc on c.categoryid = cc.categoryid  left join charity.charities ch on cc.charityid = ch.charityid      and ch.isapproved = 1 and ch.isdeleted = 0  group by c.categoryid, c.categoryname , c.isdeleted  order by c.categoryname 	0.0236737239482721
3526154	18428	how to sort by date from mysql using php	select *  from persons  where date_sub(curdate(),interval 15 day) <= str_to_date(kdate, "%c/%d/%y") order by str_to_date(kdate, "%c/%d/%y") asc 	0.00494714457241391
3527066	14668	oracle sql query count group by timestamp substring	select   substr(timestamp, 1, 8),   count(*) from   my_table group by   substr(timestamp, 1, 8); 	0.282180483534135
3531536	25378	how can i select distinct records by a name?	select application, id, tagname  from  (select application, id, tagname,   row_number()  over (partition by tagname order by tagname) rn   from table  ) x   where rn =1 	0.00186646334383129
3533173	30867	mysql: how do i remove the first row?	select coalesce(unix_timestamp(date(p.published_at)),0) as 'day',         coalesce(sum(case when p.status = 2 then p.value end),0) as 'total_accepted',        coalesce(sum(case when p.status = 1 then p.value end),0) as 'total_open',        coalesce(sum(case when p.status = 3 then p.value end),0) as 'total_declined',        coalesce(sum(case when p.status !=0  then p.value end),0) as 'total_published' from posts as p where p.published_at is not null group by date(p.published_at); 	0.000407210015728105
3558337	17665	counting groups of data in sql	select   codefield,   count(codefield)  from table  group by codefield  having count(codefield) < 12 	0.00392700946310229
3565272	12235	data transformation with sql	select cc.new_code,        max(case customer when 'c1' then old_code else null end) c1,        max(case customer when 'c2' then old_code else null end) c2 from customer_code cc group by cc.new_code order by cc.new_code 	0.525505404468345
3567620	19292	sql - fetch latest row with data in specific column or just latest row if no data in that column	select  user_id, address1  from    transaction t  where   user_id = 70005      and row_id =          ifnull(           (select max(row_id)           from transaction ti           where ti.user_id = t.user_id and address1 is not null),          (select max(row_id)           from transaction ti           where ti.user_id = t.user_id )          ); 	0
3568754	1482	get a complete list of unique values from multiple columns in multiple tables	select userid from table1 union select userid from table2 union select userid from table3; 	0
3570477	23903	query to group by maximum depth of postgresql ltree?	select     cat.id     cat.name,     cat.tree from     public.categories as cat where     cat.name = 'shania twain' and    nlevel(cat.tree) = (select max(nlevel(tree) from public.categories where cat.name='shania twain')) 	0.00775510842111758
3575295	12755	not equal to query for sql server	select * from merchant   where packageid not in (21, 22, 23) 	0.698125431202333
3577656	35899	sql table function or means to tell if identity column has been used?	select ident_seed(table_name) as seed,     ident_incr(table_name) as increment,     ident_current(table_name) as current_identity,     table_name from information_schema.tables where objectproperty(object_id(table_name), 'tablehasidentity') = 1     and table_type = 'base table' 	0.317714107748296
3604780	39861	what's the best t-sql syntax to filter for an id that has a count of x or at least x or at most x in a joined table?	select id from   members inner join comments on members.memberid = comments.memberid group by id having count(*) > 100 	0
3634382	26695	tsql/sql 2005/2008 return row from one table that is not in othe table	select a.id,      case when b.id is null then 'not found' else 'found' end as status from tablea a     left join tableb b on a.id = b.id 	6.72627269122015e-05
3671513	1510	how to move data	select id, max(col1) col1, max(col2) col2 into newtable from [table] t  group by id 	0.0462857141816874
3695369	22526	sql how to remove duplicates within select query?	select max(owner_name),          dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') as startdate  from   mytable  group by dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') 	0.0650295159457341
3714687	2896	find max value without aggregate operator in mysql	select <value> from <yourtable> order by <value> desc limit 1 	0.145746544208171
3729630	38083	converting sql number into a time, to perform date comparisons	select time(substr(digits(end_time),1,2) concat ':' concat substr(digits(end_time),3,2) concat ':' concat substr(digits(end_time),5,2)) - time(substr(digits(start_time),1,2) concat ':' concat substr(digits(start_time),3,2) concat ':' concat substr(digits(start_time),5,2)) from table1; 	0.0180708337877832
3734095	27101	order rows in join table mysql	select pay1.date_begin,        pay1.date_end,         pay2.date_begin,        pay2.date_end,        datediff( pay2.date_begin, pay1.date_end)      from (select *               from `payment_employees`               order by date_begin) as pay1           left join (select *                          from `payment_employees`                          order by date_end) as pay2              on pay2.date_begin > pay1.date_end     group by pay1.date_begin     order by pay1.date_begin asc 	0.0389522232815658
3735724	39437	find top contributers from db	select username from tablename order by postcount desc limit 10 	0.0014505490757081
3739213	30083	return 1 result per left join	select     p.id, p.name, max(f.time) as lastflight from     people p     left join flights f on p.id = f.person_id group by     p.id, p.name 	0.034810545759183
3752313	20076	ssas - facts that happened over a time range	select  [measures].[numberx] on columns from    [mycube] where   ([start date].[refdate].firstmember:[start date].[refdate].&[2009-12-31t00:00:00],         [end date].[refdate].&[2010-01-01t00:00:00]:[end date].[refdate].lastmember) 	0.00640190222656301
3761337	5662	mysql select with find_in_set with two stringlist	select count(games.id) as relevance, group_concat(gamesgenres.genre) as genres, games.* from games, gamesgenres where ('sci-fi' in (gamesgenres.genre) or 'soccer' in (gamesgenres.genre) or 'fps' in (gamesgenres.genre)) and gamesgenres.game = games.genres group by games.id order by relevance desc; 	0.265934200439694
3787483	6933	mysql order by count distinct	select   version,   count(*) as num from   my_table group by   version order by   count(*) desc 	0.120563777215608
3790722	25507	find the highest value from a column for each unique value in another column with mysql	select m.id, m.my_group, m.score  from (     select my_group, max(id) as maxid     from mytable     group by my_group ) mm inner join mytable m on mm.my_group = m.my_group     and mm.maxid = m.id 	0
3790818	32365	transform multiple queries into single row	select   (  select count(*)    from tblcases   where dateassigned between @startdate and @enddate  ) as 'cases opened' ,  (select count(*)    from tblcases   where closeddate between @startdate and @enddate  ) as 'cases closed' ,  (select count(*)    from tblticket   where dateissued between @startdate and @enddate  ) as 'tickets issued' ,  (select count(*)   from tblwarning   where dateissued between @startdate and @enddate  )  as 'warnings issued' from dual 	0.00148640483700229
3792952	40905	how to create query to select records which contain any of the defined values in any row?	select     ... from     ... where     column_1 in (string1, string2...string10)     or column_2 in (string1, string2...string10) 	0
3793609	37893	get the list of data from one table, and some count of records from another, is it possible to do in one query?	select c.id,        c.name,        count(t.id) as count_of_tours   from countries c   left join tours t          on t.id_country = c.id  group by c.id,           c.name  order by c.order 	0
3804539	7307	retrieve list of all sps with some condition	select object_name(object_id)  from sys.sql_modules where  objectproperty(object_id,'isprocedure') = 1 and      definition like '%studentid%' 	0.000704681274497097
3805859	35412	how to use a composite key with the in keyword in ms access	select  c from    mytable t1 inner join         (         select  distinct                 a         ,       b         from    othertable         ) t2 on      t1.a = t2.a         and t1.b = t2.b 	0.790271167652103
3809375	29213	counting null data in mysql	select sum(case when x.status = 'single' or x.status is null then 1 else 0 end) as single,        sum(case when x.status = 'married' then 1 else 0 end) as married   from (select distinct                t.name,                t.status           from your_table t) x 	0.0598817074562608
3813310	14932	sql - selecting first matching record for join	select          items.member_id, items.item_id, items.title, photo.photo_id, photo.blob_id, photo.image_width, photo.image_height from          items join photos on items.item_id = photos.item_id join (select item_id, min(sort_order) as min_sort_order         from photos         group by item_id) min_photo on photos.item_id=min_photo.item_id and photos.sort_order=min_photo.min_sort_order where items.member_id=1 order by items.title; 	0.000192420249785224
3819315	4295	sql server, is there any central table to get meta data of all tables?	select * from sys.objects select * from sys.columns 	0.000138638013267533
3823935	7947	sql: get list of numbers not in use by other rows	select     new_number from     generate_series(1, 1000000) as new_number         left join tbl_acct_numbers on new_number = acctnum where     acctnum is null; 	6.25022517748546e-05
3828098	5671	how to return autoincrement value in insert query in sqlite?	select last_insert_rowid() 	0.0333644651440371
3828842	7394	how to like two columns in one sql statement	select aa, bb from a, b where a.aa like '%' + b.bb + '%'    or b.bb like '%' + a.aa + '%' 	0.0111102161282652
3829918	20852	mergin two tables from different databases	select id, date, headline, text  from db1.dbo.articles1 union all select id, date, headline, text  from db2.dbo.articles2 	0.000432730370384292
3830528	5390	select with two counts on same column	select month(date) as month,         count(distinct case when field = 1 then ip end) as f1,        count(distinct case when field = 2 then ip end) as f2 from table_name  where field in (1,2) group by month 	0.000397338503198933
3831515	8742	select a set of values as a column without create	select q.query_id, t.table_id from (     select 1 as query_id     union all     select 2      union all     select 3      union all     select 4      union all     select 5  ) q  left outer join mytable t on q.query_id = t.table_id 	0.000582171756812113
3838966	19377	select * from tbl where id>=5 /* then add the result from id<5 to query */	select * from tbl order by id >= $id desc, id asc 	0.0104460055005798
3856854	28119	postgresql serialize	select * from table where field ~* 'sometext'; 	0.633438561419422
3863307	15403	join two tables at the same server	select h.code,eh.defaultname  from hotels h  join [db2].dbo.hotels eh on h.code = eh.code 	0.00122629822824797
3871749	21041	multiple field report, with custom counts in mysql	select c.course_name,        count(distinct ug.user_id) as "enrolled",        count(distinct ch.user_id) as "started" from courses c left join usergroups ug on ug.course_id = c.id left join coursehits ch on ch.course_id = c.id and ch.page_id != 4 group by c.course_name 	0.158704459069361
3877182	36343	sql sort numeric then alphabetically	select  * from    (         select '10-20' as col1         union all select '20-40'         union all select '50-60'         union all select 'v'         union all select 'k'         union all select 'r'         union all select 'a'         union all select '12 month'         union all select '1 month'         ) s1 order by         case             when col1 rlike '[0-9][0-9]-[0-9][0-9]' then 1             when col1 rlike '[0-9]+ month' then 3             else 2         end ,       case             when col1 rlike '[0-9][0-9]-[0-9][0-9]' then cast(col1 as decimal)             when col1 rlike '[0-9]+ month' then cast(col1 as decimal)             else col1         end 	0.0651857543268307
3880405	25517	how do i combine two selects from one table where one has a group by and the other has a distinct	select *    from (          select ponumber, count(requestnumber) as "innumofrequests", sum(amount) as "sumofamounts"            from tableview           group by ponumber         ) a,         (          select distinct ponumber, (10 * ceiling((datediff(day, poapproveddate, getdate()))/10)) as "binofdayssincepoapproved"            from tableview         ) b  where a.ponumber = b.ponumber 	0
3891244	33341	how to add row number column base on duplicated records that currently ordered	select *, dense_rank() over (order by sort)  from (select *, sort = min(id) over (partition by page_order)          from #tbl) c  order by c.id 	0
3902628	19317	how to use query results in another query?	select x.id      , t.balance      , t.date   from your_table t      , (select max(id) id,         extract(year_month from date) as yyyymm         from transactions         group by yyyymm) x  where t.id = x.id 	0.187361895308406
3903749	21037	mysql inclusion/exclusion of posts	select t.*, i.*, r.*, g.*, e.* from posts t left join postprivacyincludefor i on i.user_id = ? and i.thought_id = t.id left join friendfilterids r on r.list_id = i.list_id and r.friend_id = ? left join following g on follower_id = t.owner_id and g.following_id = ? and g.friend=1 left join postprivacyexcludefrom e on e.thought_id = t.id and e.user_id = ? 	0.0108828195515936
3904898	5870	sql query - comparing two items on distinct item	select        evt,       max(case when pers='john' then rank end) as john,       max(case when pers='paul' then rank end) as paul,       max(case when pers='john' then rank end) -                     max(case when pers='paul' then rank end) as difference from yourtable  where pers in ('john','paul') group by evt 	9.11425987185624e-05
3909557	13056	forming sql query for detail and subtotals (mysql)	select download_date, image_file_id, credits      group by download_date, image_file_id with rollup 	0.577360577976401
3910489	1540	how can i find identical tables in mysql and php?	select if(count(*) = (select count(*) from table1) and count(*) = (select count(*) from table2),1,0) as result from (     select * from table1     union     select * from table2 ) tables_joined 	0.00565256775556625
3912968	17072	sql: filter by date	select      s.*,      s.date > d.min_date_10 as status from signups s     join (         select min(date) as min_date_10 from (             select date from signups order by date asc limit 10         ) a     ) d where idevent = 1 	0.0986358023714489
3914582	40988	mysql count query	select   refference_id,   count(*) from   table group by   refference_id 	0.356178943888014
3939995	24195	sql query to show multiple entries and its count	select col1, col2, count(*) from yourtable group by col1, col2 having count(*) > 1 	0.000214363519831508
3945890	23997	how do i count how many of these columns have a value in sql?	select   id,   sum(     case when item1 is null then 0 else 1 end     +     case when item2 is null then 0 else 1 end     +     case when item3 is null then 0 else 1 end     +     case when item4 is null then 0 else 1 end     +     case when item5 is null then 0 else 1 end     ) 'count' from     tablename group by     id 	0.000157966570109889
3950976	38515	doing multiple mysql counts in one query?	select count(*) as full_amount,     count(address) as has_address,     count(name) as has_name from table; 	0.115119833803004
3952854	1990	sql query to get the structure of a table of datbasea in servera	select      c.table_name     ,c.column_name     ,c.data_type     ,c.character_maximum_length from      information_schema.tables t      inner join information_schema.columns c on t.table_name=c.table_name where      t.table_type='base table' order by      c.table_name 	0.000616302640523827
3962138	19413	multiple rows, one query	select name, (select gpa from gpas where name = t1.name and semester = 'winter') as `gpawinter`, (select gpa from gpas where name = t1.name and semester = 'spring') as `gpaspring` from gpas t1 	0.00660847138374913
3972949	17894	selecting rows where there are at least x rows with some values in a column via sqlite3?	select * from books where bookid in      (select bookid from books group by bookid having count(*) >= 3) 	0
3974501	17549	oracle select count(*) … group by … not returning rows where the count is zero	select a.empid, nvl(sum (total_records),0) total_records     from (select '2____' empid from dual union select '3____' from dual                                         union select '99____' from dual) a         left outer join        (select id,                  (case when id like '2%'  then '2____'                        when id like '3%'  then '3____'                        when id like '99%' then '99____'                  end) empid,                  total_records          from tr         where ( id like '2%' or id like '3%' or id like '99%')) b       on a.empid = b.empid group by a.empid; 	0.0485862494070952
3987336	40172	find nearest gps point to the user location form a list	select lat, lon, acos(sin($lat)*sin(radians(lat)) + cos($lat)*cos(radians(lat))cos(radians(lon)-$lon))$r as dist from mytable order by dist desc 	0.000324993031608591
3999491	9675	how do i select all the columns from a table, plus additional columns like rownum?	select rownum, table.* from table 	0
4008241	8457	mysql - three joins on the same table	select sp.fullname studentname, fp.fullname fathername, mp.fullname mothername   from students s  inner join persons sp on (s.student_id = sp.person_id)  inner join persons fp on (s.father_id = fp.person_id)  inner join persons mp on (s.mother_id = mp.person_id) 	0.00798159217225836
4017079	12286	pervasive sql 10 join one table, onto another, onto another	select p.productid,           p.price,           x.max_eta      from products p left join porows r on r.productid = p.productid left join (select po.id,                   max(po.eta) as max_eta              from po po           group by po.id) x on x.poid = r.poid 	0.000859625456418079
4023999	23137	null value column and not exists t-sql	select  *                    from    [tbl_web_company]                  where   [name]          = @name                 and     [address1]      = @address1                 and     [address2]      = @address2                 and     [city]          = @city                 and     isnull([province_id],99999) = isnull(@province_id,99999)                 and     [postal_code]   = @postalcode                 and     [contact_phone] = @phone                 and     [contact_fax]   = @fax                 and     isnull([deleted], '1990-01-01') = isnull(dbo.pvd_fn_getdeleteddate(@id, @active), '1990-01-01')     begin         select 'update'     end     else     begin         select 'no update'     end 	0.0925976097994137
4044736	35838	sql query comparing rows from single table	select combo1.gene, combo2.gene, count (gene2.goterm) from (select distinct gene from gene) combo1 cross join (select distinct gene from gene) combo2 join gene gene1 on combo1.gene = gene1.gene left join gene gene2 on combo2.gene = gene2.gene     and gene1.goterm = gene2.goterm and gene1.auto < gene2.auto group by combo1.gene, combo2.gene order by combo1.gene, combo2.gene 	0.000402643663893138
4068588	14943	validate telephone number in sql server 2000	select number   from numbertable  where dbo.fn_pcre_match(number, 'someregex') = 1 	0.643471445970594
4075971	36291	creating a column from the existence of matching rows in an other table?	select     p.*,      case when exists                  (                     select *                      from pets                      where personid = p.id                  )                  then select 1                   else select 0                   end     as haspets from person p 	0
4089820	3283	selecting all rows with highest (relative) timestamp	select t3.* from your_table t4 join (     select t2.[key], t2.effectivedate, max(t2.id) as id     from your_table t2     join      (         select [key], max(effectivedate) as effectivedate         from your_table         where appname = 'app1'         and effectivedate <= getdate()         group by [key]     ) t1     on t1.[key] = t2.[key] and t1.effectivedate = t2.effectivedate     where t2.appname = 'app1'     group by t2.[key], t2.effectivedate ) t3 on t3.id = t4.id 	0
4096078	14584	mysql: not having a string like in a group?	select *, count(*) as totalvisits from `visitorlog` where      visitorid not in          (select visitorid from `visitorlog` where `url` like '%page=checkout%') group by visitorid 	0.746170136385969
4105368	28614	how can i determine if an oracle table has the rowdependencies option set?	select owner, table_name, dependencies from dba_tables; 	0.0140906052526349
4107067	18086	how to create a join across two foxpro databases using the ms ole db provider?	select        a1.whatever,       b1.sales1    from       customers a1,       2009\sales b1    where        a1.customerid = b1.customerid union all select        a1.whatever,       b1.sales1    from       customers a1,       2010\sales b1    where        a1.customerid = b1.customerid union ... 	0.363727322272437
4120024	30511	query multiple dates not greater than the current date	select e.id,        e.picture,        e.name,        e.venue,        e.city   from events e  where not exists(select null                     from event_dates ed                    where ed.event_id = e.id                      and ed.start_date >= current_date()) 	8.36430277192587e-05
4122355	33345	how do i count rows in mysql?	select first, last, product_category, count(product_code) from <table> order by last, first group by first, last, product_category 	0.0203376049089747
4122601	4586	select distinct and one another column of the id	select distinct id, department  from tbl 	0
4123036	25595	how to subtract time in mysql	select date(now()-interval 15 day) 	0.0107228576063475
4124362	26031	sql sum( ) over different periods?	select  sum(case when tradedate between '2004-01-01' and '2010-08-31' then amount end),         sum(case when tradedate between '2006-01-01' and '2010-08-31' then amount end),         sum(case when tradedate between '2010-01-01' and '2010-08-31' then amount end) from    funds join    cashflow on      cashflow.id = funds.id 	0.00838316098851626
4129673	8696	query multiple tables - return 1 match	select f.id, name from foodlist f join addresses a on (f.id = a.entryid) $where 	0.0111800284553833
4137776	29564	select the minimum of two dates	select least(date_1, date_2) from dual; 	9.01270765188484e-05
4141440	20359	how to select one row if condition true, other row if condition false in sql?	select sum(case bt.stage_id              when 2 then bt.novartis_total              else 0            end) as 'novartistotal' from   budget_totals bt,        rfp_proposal rp where  ( bt.rfp_proposal_id = 1           or bt.rfp_proposal_id = 22 )        and rp.status_type = 'accepted'        and rp.vendor_id = 2        and ( rp.id = 1               or rp.id = 22 ) 	0
4150075	39642	selecting specific rows from deleted table within a trigger	select customerid from deleted where customerid not in (select customerid from customerorders) 	0
4159000	29387	sql query from two tables	select username   from customer  where cus_email = ? and cus_password = ? union select adminname as username   from admin  where admin_email = ? and admin_password = ? 	0.0107209605576502
4159998	3497	how can i get the foreign keys of a table in mysql	select     `column_name`,      `referenced_table_schema` as foreign_db,      `referenced_table_name` as foreign_table,      `referenced_column_name`  as foreign_column  from     `information_schema`.`key_column_usage` where     `constraint_schema` = schema() and     `table_name` = 'your-table-name-here' and     `referenced_column_name` is not null order by     `column_name`; 	0
4170367	4817	mysql: alternative to order by something limit 0,1	select * from mytable where column = something and date = (select min(date)             from mytable); 	0.7737559267211
4188564	39430	how do i map a derived property on a base class using nhibernate?	select ..., this_.damagecosttotal from assessment this_ order by this_.damagecosttotal 	0.0632570837366277
4190405	13952	reading most recent values in a join without performing a nested select	select fp.id,           fp.user_id,           count(a.id) as num_replies,           c.date as latest_activity_time,           c.user_id as latest_activity_user_id      from forum_posts fp left join comments a on a.object_id = fp.id          left join (select x.object_id,                   x.date,                    x.user_id              from comments x              join (select t.object_id,                           max(t.date) as max_date                      from comments t                  group by t.object_id) y on y.object_id = x.object_id                                         and y.max_date = x.date) b on b.object_id = fp.id     where fp.deleted != 1  group by fp.id 	0.00115961902587343
4196497	37142	select statement mysql	select * from testtable where "http: 	0.510257170049618
4203213	32343	select all but the latest row	select * from loginhistory l  where user_id = 'testuser@company.com'  and l.timestamp < (select max(timestamp) from loginhistory where user_id = 'testuser@company.com'); 	0
4215426	37211	passing comma-separated value from .net to stored procedure using the value in "in" sql function	select *     from table     where field in (select field from dbo.myfunction(@param1)) 	0.17127082721019
4218536	40968	join results from two sql tables	select   p.state,   p.gender,   sum(      ( select count(1) from examtest e        where e.personid = p.personid        and e.examresult > 0 ) ) as examcount,   sum(      ( select count(1) from sampletest s        where s.personid = p.personid       and s.result > 0 and s.result < 4) ) as samplecount from   person p group by   p.state,   p.gender 	0.0108023933502201
4218727	39611	sp_who2 blkby sleeping process awaiting command	select     p1.spid as blockedspid, p2.spid as blockingspid, ... from      master..sysprocesses p1     join     master..sysprocesses p2 on p1.blocked = p2.spid 	0.655755941908306
4220896	39517	mysql select dates in the past: problem with max and group by	select jid, max(start) as start from dates group by jid having max(start) < now(); 	0.0096839439915392
4226672	14477	mysql query to find duplicate having more than (n) entries	select id, user_id   from table  group user_id having count(1) > 1 minus select min(id) id, user_id   from table  group by user_id 	0
4237608	997	querying the restrict_references pragma	select text from all_source where upper(text) like '%pragma restrict_references%' and owner = :owner and name = :package_name and type = 'package'; 	0.104164108736901
4241561	9590	single sql query to fetch results from tables with many-many relationship	select   i.* from   favorites f   join images i on f.img_id = i.img_id where   f.user_id = <user id> 	0.0012812928026326
4246001	25708	t-sql extra column in group by. how to include in results but exclude from grouping	select     a.cnumber, a.formsubmitted, a.score from         dbo.vw_msa a inner join  (select cnumber, max(formsubmitted) as maxsubmitted  from dbo.vw_msa where     (score is not null) group by cnumber) as b on a.cnumber = b.cnumber and a.formsubmitted = b.maxsubmitted 	0.000876080852491487
4258726	2528	sql query which counts the top search terms and orders by that	select d1.customerid,searchterm,createdon,d1.timessearched from  (     select customerid, count(searchterm) as timessearched         from searchlog          where createdon >= dateadd(day, datediff(day, 0, getdate()), -5)         group by customerid         order by count(searchterm) desc ) as d1 inner join searchlog on    d1.customerid=searchlog .customerid 	0.000826544270353753
4266263	2469	sqlite and inserting the current date in utc format	select datetime('now') 	0.00117560176856924
4267069	34954	mysql query to fetch data from multiple tables	select p.productid, p.name, p.price, count(pv.viewid) as totalviews, count(s.salesid) as totalsales  from products p left join sales s on s.productid = p.productid left join productviews pv on pv.productid = p.productid group by p.productid, p.name, p.price 	0.000959685390687765
4267687	199	mysql union ordering	select     *, 1 as sortkey from      devices where     live = 'true'     and category = 'apple' union select         *, 2 as sortkey     from         devices     where         devicelive = 'true' order by sortkey, listorder 	0.563915006528442
4271203	6336	sort db2 sql results by where clause	select *  from media  where media_title like 'query'      or media_title like 'query string'      or media_title like 'query string to search for'  order by case      when media_title like 'query' then 1     when media_title like 'query string' then 2     when media_title like 'query string to search for' then 3 end 	0.733678227234863
4276785	743	how to get sum from joined table b with multiple results againts one row in table a?	select * from spareparts s join (select itemid, sum(quantity) as quantity from stockq group by itemid) as q on s.itemid = q.itemid 	0
4284344	227	group by on date with sql query?	select id,s.no,datefr,dateto  from your_table group by id,s.no,datefr,dateto 	0.209468383420285
4307218	34736	how to check for existing records before running update code?	select sequentialnumber from mytable where sequentialnumber between $startnum and $endnum 	0.0129239499572668
4337579	21502	sql subqueries, grouping and a bit of math	select       table1.a,       sum(iif([b]=1,1,0)) as count1,       count(table1.a) as total,       (sum(iif([b]=1,1,0))/ count(table1.a)) * 100 as percentofones from       table1 group by       table1.a; 	0.687920649704523
4349601	7966	recursively selecting top most recursion in mysql	select id_group, coalesce(p4.id_group, p3.id_group, p2.id_group, p1.id_group, g.id_group)    as top_id_group from shop_groups_group_rel g left join shop_groups_group_rel p1 on p1.id_group = g.id_parent left join shop_groups_group_rel p2 on p2.id_group = p1.id_parent left join shop_groups_group_rel p3 on p3.id_group = p2.id_parent left join shop_groups_group_rel p4 on p4.id_group = p3.id_parent 	0.00388537062844965
4352916	37928	sql column true or false - use a view?	select *  from news where ((@live_only=true and showonsite=true) or (@live_only=false)) 	0.526669549198363
4356153	12423	mysql: merging different entities in one query	select 'rating' as type, value as r_val, null as c_val from rating union select 'comment' as type, null as r_val, comment_text as c_val from comment 	0.00400077313432576
4365970	12551	finding blocking/locking queries in ms sql (mssql)	select * from sys.dm_exec_requests where db_name(database_id)='yourdbname' and blocking_session_id <>0 	0.386241572447634
4370820	29792	is there a way, in oracle, to join multiple row lines into a single one, using two tables, where the final values are separated by commas?	select name, listagg(car, ',') within group (order by car) as cars from   (select name,car from table1, table2 where table1.idn=table2.idc) group by name; 	0
4376750	1378	mysql multiple selects & joins	select s.*,p.om_quote_no,o.project_ref from  orders as ord,porders as p,suppliers as s where o.supp_short_code = p.supp_short_code and      o.supp_short_code = s.supp_short_code 	0.727932679148072
4381163	37463	datediff rounding in sql server	select case           when datediff(hh, lastrundatetime, getdate()) >= 1 then 1           else 0         end 	0.785960588953864
4382379	2339	how to list the top 10 most duplicate rows?	select vote, count(*) from votes group by 1 order by 2 desc limit 10 	0
4382462	31184	t-sql two where clauses on same column	select name, num from tbl where name in (     select name from tbl     where num in (10, 20)     group by name      having count(*) = 2  ) and num in (10, 20)  	0.00515843909698577
4394612	403	query to return results based on row_count in associated table?	select        m.matchid,        {whatever other columns},       count(*) matchcount    from         match m,       matchshots ms    where            m.matchid = ms.matchid       and ( m.shot_limit = 1 or m.shot_limit = 3)    group by       m.matchid    having        matchcount >= m.shot_limit 	0.000183659697943349
4406854	18536	efficient query for finding duplicate records	select     * from     transactions t1         inner join     transactions t2         on             t1.terminal = t2.terminal and             t1.amount = t2.amount and             datediff(minute,t2.transactiondate,t1.transactiondate) between 0 and 10 and             t1.transactionid > t2.transactionid 	0.00424824644128948
4407030	21301	get the row with the highest value in mysql	select  t.* from    table t inner join         (             select  fileid,                     max(seqid) maxseqid             from    table             group by    fileid         ) m on  t.fileid = m.fileid             and t.seqid = m.maxseqid 	0
4407107	14086	how to filter results based on age from mysql database	select * from table where datediff(current_date, dob) >= (12 * 365.25) and datediff(current_date, dob) <= (24 * 365.25) 	0
4407161	32947	find duplicate strings in database	select * from `yourtable` where `yourcolumn` in (     select `yourcolumn`     from `yourtable`     group by `yourcolumn`     having count(*) > 1 ) 	0.00350808146624974
4412651	7367	how to convert a.b.c.d ip records to an ip value using a function in mysql?	select id, ip, inet_aton(ip) as ip_value from your_table; 	0.0044400570254491
4413532	39054	t-sql merge records based on criteria	select name, email, isnull(sum(score1),'') as score1, isnull(sum(score2),'') as score2     from score      group by name, email 	8.29331310012152e-05
4415875	4937	order by amount of entries in mysql	select date(`datetime`) as `date` from your_table group by `date` order by count(*) desc limit 1 	0.000251586794626712
4422427	38132	mysql group by using two columns	select tm.manufacturername,sum(tb.quantity) as qty,sum(tb.afterdiscount) as afterdiscount from tblbasket as tb inner join tblstock as ts on ts.productcode = tb.productcode and tb.status=3 left join tblmanufacturer as tm on tm.manufacturerid=ts.manufacturerid group by ts.manufacturerid order by qty desc 	0.0145728046372461
4441325	23402	access last row added to table - php	select * from newsitems order by itemid desc limit 1 	0.000171629639043377
4448848	39690	sql server, selecting random item from table where id used across another table	select top 1 * from     root r         left join     rootitem ri         on             r.id = ri.rootid and             ri.accountid = @accountid where     r.private = 0 and     ri.id is null order by     newid() 	0
4466720	9974	sql server view when trying to use the same columns multiple times	select  computer_id ,       max(case when key = 3 then value end) as name ,       max(case when key = 4 then value end) as ip ,       max(case when key = 5 then value end) as user from    yourtable group by         computer_id 	0.00491137310244695
4470773	14141	get mysql rows where 2 words match	select k2d.`data_id`,         k2d.`keyword_id`  from   keywords2data as k2d         inner join keywords as k           on k2d.`keyword_id` = k.`id`  where  k.`keyword` in ( 'dog', 'sled', 'rex' )  group  by k.keyword  having count(*) = 3 	0.000351664928924368
4473360	22558	sql grouping and then un-grouping in one query	select cat, mouse from pets where cat in (select cat          from pet          group by cat          having count(mouse) > 3); 	0.0355967815230533
4481290	23432	sql join: avoid duplicate entries while joining two tables?	select distinct ...   from a   join b on ... 	0.000805457209340373
4481940	10165	how to format oracle sql query	select 'the price of [' || prodname || '] is [' || prodajnacena || '] lv'  from your_table_name; 	0.443301294526593
4491534	39460	showing only actual column data in sql*plus	select a || ';' || b || ';' || c || ';' || d from t where ... 	0.00270837682971633
4512337	9721	get top 10 from database with some calculation	select * from photos order by (p_up-p_down) desc limit 10 	0.000146960437796813
4516785	29949	getting the ranking of a photo in sql	select  p.photoid,         isnull(v.countvotes,0) countvotes,         rank() over(order by isnull(v.countvotes,0) desc) rankincategory,         rank() over(partition by p.categoryid order by isnull(v.countvotes,0) desc) rankincategory from    photos p left join          (             select  photoid,                     count(photoid) countvotes             from    votes v              group by    photoid         ) v on  v.photoid = p.photoid 	0.0310690150958241
4518663	29222	sql string contains only	select field from yourtable where field not like '%[^n]%' and field <> '' 	0.0167261116248836
4529909	35349	mysql optimised code for 2 tables?	select t1.id, t1.int1, t1.int2 ... t2.blobdata from table1 t1, table2 t2  where t1.id = t2.id and t1.id = <your input id> 	0.501778891895154
4539518	5371	usage of array in sql possible?	select r.regionid,        t.townid,        t.city,         t.stateinitials from region_townpage r join townpage t on r.townid = t.townid where r.regionid = @regionid 	0.285589777672276
4542617	11719	building a query with two tables using sum	select affiliate_id, sum(amount) total_amount  from commissions group by affiliate_id  having total_amount > 30 	0.17472944531146
4551174	20509	mysql query except and where	select * from categories where id != $post_id order by id desc  	0.473675054714696
4567272	27567	mysql count() total posts within a specific criteria?	select    count(*) as total from    forum_topics join    forum_posts on topic_id where    forum_topics.deleted = 0    and forum_posts.deleted = 0    and forum_posts.forum_id = '{$forum_id}' 	0
4569859	29665	wrapping multiple columns in a single column	select      isnull(lastmodifieddate,createddate) as activitydate,     isnull(lastmodifiedby,createdby) as user .... 	0.00149931342576993
4570745	17255	mysql query with 2 count() of other tables with where conditions	select   sports.id,   sports.name,   sports.slug,   sports.description,   ifnull(count( distinct seasons.id ), 0) as distinctseasons,   ifnull(count( distinct competitions.id ), 0) as totalcompetitions from    sports   left join seasons on sports.id=seasons.id_sport   left join competitions on seasons.id = competitions.id_season group by   sports.id; 	0.00633773414687637
4574099	12571	how to calculate the total hours	select     sum(cast(reverse(substring(reverse(timecol),5,8000) as int), id from     mytable group by     id 	0
4597586	8823	oracle date / order by question	select monthyear,yr,month,count(req_id) from ( select (to_char(req_date,'mm/yyyy')) as monthyear, to_char(req_date,'yyyy') yr, to_char(req_date,'mm') month, req_id from   requisition_current t ) x group by monthyear,yr,month order by yr, month 	0.697946369859715
4600400	17139	how can i join pairs of records in a single table sorted chronologically (using mysql)	select t.id,t.type,t.time,t2.id,t2.type,t2.time from table t left join table t2  on (t.type = 'a' and t2.type = 'b' and t.time < t2.time)  where t2.id is not null group by t.id 	0
4602908	36403	sql joining data from other tables	select item.description, item-custom.description1, item-custom.description  from item left join item-custom on item.no = item-custom.itemid 	0.000727113790892878
4605627	27857	how to sort mysql coloumn that has data in bytes kb mb gb?	select size   from t  order      by case when size like '%gb' then power(1024, 3) * substr(size, 1, length(size) - 2)             when size like '%mb' then power(1024, 2) * substr(size, 1, length(size) - 2)             when size like '%kb' then power(1024, 1) * substr(size, 1, length(size) - 2)             when size like '%b'  then                  substr(size, 1, length(size) - 1)         end desc; + | size  | bytes      | + | 1gb   | 1073741824 | | 10mb  | 10485760   | | 100kb | 102400     | | 1000b | 1000       | + 	0.00265309045890119
4629011	2009	how to count all stored procedure in the sql server for a database?	select count(*) from sys.procedures 	0.0218089870281067
4637772	1691	simplify two mysql queries by merging them into 1?	select sum(if(type='in',1,0)) as in_count,         sum(if(type='out',1,0)) as out_count from   referrals where  author = '{$author}' and        ip_address = '{$ip_address}' limit  1 	0.00856696305279839
4645456	23354	get table names from a database	select * from information_schema.tables where table_type='base table' 	6.49131911704166e-05
4647536	3151	how to count number of deleted rows from one table in delete + join structure?	select count(*) as sale_rows from ic where ic.sale = '5' 	0
4647700	34831	sql stored procedure set variables using select	select @currentterm = currentterm, @termid = termid, @enddate = enddate     from table1     where iscurrent = 1 	0.735243448534502
4649725	33505	sql query help - top n values of t.a grouped by t.b, t.c	select tasklogid,        taskid,        hostname,        rundate from   (select tasklogid,                taskid,                hostname,                rundate,                @num := if(@group = concat(taskid, hostname), @num + 1, 1) as row_number,                @group := concat(taskid, hostname) as dummy         from   tasklog) as x where  row_number <= 5; 	0.0028590313729891
4653975	32781	how to check if one column value is greater than another in mysql	select * from mytable where time_taken > time_spent 	0
4658697	1895	sql counting total rows with distinct?	select 'field1' as fieldname, cast(field1 as char) as fieldvalue, count(*) as count     from table group by field1  union all   select 'field2' as fieldname, field2 as fieldvalue, count(*) as count     from table group by field2 	0.00038375974662384
4668902	12881	mysql group by to display latest result	select  * from    (         select  distinct meta_value         from    postdata pd         where   pd.meta_key = 'date'         ) pd join    post p on      p.id =          (         select  post_id         from    postdata pdi         join    post pi         on      pi.id = pdi.post_id         where   pdi.meta_key = 'date'                 and pdi.meta_value = pd.meta_value         order by                 pi.post_date desc, pi.id desc         limit 1         ) 	0.000339597614445743
4680046	34957	can we use a sql data field as column name instead?	select  md.id, md.cat, m1.value as context1, m2.value as context2 from    (         select  distinct id, cat         from    mytable         where   id = 1         ) md left join         mytable m1 on      m1.id = 1         and m1.cat = md.cat         and m1.context = 'context 1' left join         mytable m2 on      m2.id = 1         and m2.cat = md.cat         and m2.context = 'context 2' 	0.0292544372027931
4680902	12233	how can i build my sql query from these tables?	select ... from table1 inner join (select memberid, sum(amount2) from table2 group by memberid) agg on table1.memberid = agg.memberid 	0.505931748320793
4683565	7211	query sql distinct field with max date, returning all fields from table	select a.columns from table a where a.id in (select top 1 b.id from table b where b.name = a.name order by b.date desc) 	0
4686919	12362	how go get entry from last year mysql	select * from `{$this->_sprefix}clicks`  where `affiliate_id` = '{$iaid}'  and `raw` = '1'  and year(`date`) = year(date_sub(curdate(), interval 1 year)) 	0
4694629	35175	mysql query help (select latest updates based on timestamp)	select d.userid,         d.userinfo,         d.updated,         u.username    from datatable d   join usertable u on u.userid = d.userid   join (select t.userid,                max(t.updated) as max_updated           from datatable t       group by t.userid) x on x.userid = d.userid                           and x.max_updated = d.updated 	0.00266030025687941
4700155	19747	sql server count on a grouped by	select x.name      , count(*) as cntnames      , sum(x.cntdetails) as cntdetails   from (         select i.name, count(*) as cntdetails           from item as i          inner join item_category as ic on i.i_category_id = ic.ic_id          inner join idetail as id on ic.ic_id = id.id_category_id          where ic.ic_id = 1002          group by i.name,id.id_category_id        ) x   group by name 	0.0304763487504035
4705673	40253	php / mysql - select id from one table excepting ids which are in another table	select * from users where id not in  (select userid from visits where date > date_sub(now(), interval 12 hour)) 	0
4712269	16740	how to remove all comments (single line --) from code	select text from   user_source where  name = 'mypackage' and    type = 'package body' and    ltrim(text) not like ' order by line; 	7.80048905094011e-05
4725768	24427	get rows affected by an update	select * from final table ( update yourtable set c1 = x where ... ) 	0.00321448636536946
4729098	17671	how can i average number of items in our sqlite database by 24-hour period?	select   avg(cast(ticketsopened as real))   from   (   select     cast(created_at as date) as day       count(*) as ticketsopened   from     ticket_count   group by     cast(created_at as date)   ) as x 	4.79822615603543e-05
4729406	18512	mysql returning the top 5 of each category	select profilename, name from (     select m.profilename, s.name,         @r:=case when @g=m.profilename then @r+1 else 1 end r,         @g:=m.profilename     from (select @g:=null,@r:=0) n     cross join menus m      left join menuitems s on m.menuid = s.menuid ) x where r <= 5 	0
4736743	39069	with hibernate, how can i query a table and return a hashmap with key value pair id>name?	select new map( max(bodyweight) as max, min(bodyweight) as min, count(*) as n ) from cat cat 	0.0115999427993966
4743487	7421	extract data from one field into another in mysql	select `id`, `name`, preg_capture('/.*?\\((.*)\\)/',`name`,1) as branch from `venues` 	0
4752543	4729	sql select on condition	select top 1 amt from table order by id; 	0.193579150159052
4763143	36020	sql for applying conditions to multiple rows in a join	select * from users inner join tags as t1 on t1.user_id = users.id and t1.name='tag1' inner join tags as t2 on t2.user_id = users.id and t2.name='tag2' 	0.0973892694435573
4766434	14411	how to get the tag list in wordpress mysql	select wp_terms.`term_id` as tagid, wp_terms.`name` as tagname, sum( tax.`count` ) as tagpostcount from `wp_terms` inner join wp_term_taxonomy tax on tax.term_id = wp_terms.term_id group by wp_terms.`term_id` 	0.00169291525993048
4788582	38641	mysql select across multiple tables with joins	select all_products.manufacturer_id, all_products.category_id, all_products.product_name, manufacturer.manufacturer_name, category.category_name from manufacturer join (  select manufacturer_id, category_id, product_name  from product_table1  union all  select manufacturer_id, category_id, product_name  from product_table2 ) as all_products on all_products.manufacturer_id = manufacturer.manufacturer_id join category on category.category_id = all_products.category_id 	0.175437784006405
4789387	6372	adding an additional column to sql result set by using two que	select cr.communication_id, cr.consumer_id, cr.action_log_id,        cal.consumer_id, cal.tips_amount, cal.last_mod_time,        singleton.avg_tips from communication_relevance as cr join consumer_action_log as cal on cr.action_log_id=cal.action_log_id cross join (     select avg(tips_amount) as avg_tips     from consumer_action_log     join communication_relevance     on consumer_action_log.sender_consumer_id=communication_relevance.consumer_id ) singleton 	0.0206407347085958
4789876	16022	sql query to get total number of students in a class	select c.id as id, c.class_name as class, count(e.student_id) as student_count  from classes as c left join enrollments as e on e.class_id = c.id  and  e.approved = 1 where c.teacher_id = 8  group by c.class_name; 	0
4805395	2031	check that values not null	select amount - coalesce(correction, 0) - coalesce(used, 0) .... 	0.0303879942338816
4806698	16196	reverse sql like	select  * from    table_name where   'awesome stuff' like field_value 	0.793058079750674
4818025	16316	how to find the relative ratio in rows in mysql	select query,url,num_clicks,num_clicks/t.totalclicks as ratio from mytable inner join (    select    query,sum(num_clicks) as totalclicks    group by query ) as t on mytable.query = t.query 	0.000166505185563731
4821114	41120	single select query to handle two conditions	select column1,column2      from table1      where isnull(coalesce(i.hyperlinkcolumn, i.picturecolumn)) != 1; 	0.0247152332114506
4827751	7610	compare two columns in a select	select column1, column2,     case       when column1 is null and column2 is null then 'true'         when column1=column2 then 'true'        else 'false'     end  from table; 	0.000454609885796048
4834600	26001	fetching a table with unique or distinct values?	select count(distinct event_id) from   posts  where  user_id = '43'    and event_id is not null 	0.00162378768660878
4842725	19576	mysql timediff count hours between 10pm to 6am	select hour(timediff('2011-01-26 23:51:20',                       '2011-01-26 15:51:10'))     as totalhours 	0.00144988528634369
4854987	40469	3 table joins one field from one table and one field from another	select c.city, t.time_slot  from cities c left join city_date d on d.city_id = c.id  left join city_time t on t.city_date_id = d.city_id and t.city_date_id = '1' 	0
4857430	20984	could a sql database return a sql result set plus a score for the results?	select top 1000 jaro('john', name) as score, name from table where name like '%john%' order by 1 desc 	0.00630949660452209
4858828	40581	sql where in (...) sort by order of the list?	select t1.* from t1 inner join (   select 1 as id, 1 as num   union all select 5, 2   union all select 3, 3 ) ids on t1.id = ids.id order by ids.num 	0.0115600061852506
4866692	11299	find rows in a table where field1 is the same and field 2 is different	select a.serial_no, a.userid, a.enrollmentid   from a tablea  where a.userid in (   select distinct a.userid from tablea  a, tablea  b where a.userid = b.userid and a.enrollmentid <> b.enrollmentid ) 	0
4872021	10526	how to get all results, except one row based on a timestamp?	select * from (   select *, row_number() over (order by loggedat desc) as rownum   from [table] t   where somecolumn = 'somevalue' ) s where rownum > 1 	0
4883995	18508	sql server 2005 query remove duplicates via date	select c.firstname, c.lastname, aspnet_membership.loweredemail, max(bill.code) as bcodes, max(bill.billdate) from dbo.client c inner join dbo.bill on c.id=bill.bid inner join dbo.aspnet_membership on aspnet_membership.userid=c.userguid left join dbo.bill b2 on bill.bid = b2.bid and    b2.code in ('asdf','xyz','qwe','jkl') and    b2.bdate > bill.bdate where b2.bid is null and ((bill.code='asdf' or bill.code='xyz' or bill.code='qwe' or bill.code='jkl') and c.lastname!='unassigned') group by lastname, firstname, loweredemail, code, bdate 	0.182522448549329
4884848	7157	php query to retrieve pal(friend) information and list thumbnails with links to pal information	select * from users u inner join pal p on p.user1_id = u.user_id inner join pictures pi on pi.user_id = p.user2_id where u.user_id = 92 	0.000181684954242745
4892412	18760	using a hidden stored procedure	select name     from sys.databases     where name like 'z%'         and create_date >= dateadd(mm,-1,getdate()) 	0.568839771814025
4901457	9739	in mysql, what is an efficient way to get only rows in a table by a distinct value in one of that table's columns?	select mt1.id, mt1.name, mt1.location  from mytable mt1 join (select min(id) as id          from mytable          group by location) mt2     on mt1.id = mt2.id 	0
4906852	22099	how to limit result returned to 1 of each (mysql+c#)	select distinct(first_name) from people 	7.90290795658317e-05
4916233	32114	retrieving date format rows in mysql	select addeddate from status where addeddate <= now() - interval 29 day 	0.000935193011379486
4920073	33080	how to add several sequence numbers to one single sql view in mysql	select folder, file,   @r = case when @g = folder then @r+1 else 1 end sequenceno,   @g := folder from (select @g:=null) g cross join tbl order by folder, file 	0.000175413696064692
4926247	13439	mysql/php determine lowest values in table with multiple value columns	select least(t.c_price1, t.c_price2) as lowest     from your_table t    where least(t.c_price1, t.c_price2) != 0.00 order by lowest    limit 5 	0
4934137	18310	merge tables and keep lowest values	select [foreign key], min(height) as height, min(weight) as weight,      min(length) as length from @yourtablevar group by [foreign key] 	0.000457887908051936
4937832	21721	omit aggregate column in sql query	select top 1 id, description from record order by created desc 	0.496575721739888
4942454	36128	how to take unique values in sql	select adress, max(a.customerid) from a left join b on a.customerid=b.customerid where points > 15 group by adress 	0.00112126361055989
4944994	18404	select query on two tables with no unique keys	select   a.col1,   a.col2,   a.col3,   b.colc  from (   select     row_number() over (partition by col1, col2 order by 1) r,     col1,     col2   from     table1   ) a,  (   select     row_number() over (partition by col1, col2 order by 1) r,     col1,     col2   from     table2   ) b   where a.r = b.r and         a.col1 = b.col1 and         a.col2 = b.col2; 	0.00056510458765721
4946701	27758	php output couple times data from a column	select * from tbl limit 9,20; 	0.000434899928149416
4959689	10059	find date stored in mysql row, find all entries after that date in one query	select *      from actions      where created_at >= (select max(created_at)                               from actions                               where key_action=1) 	0
4961013	37887	concatenate two columns with equal space	select countyname + space(20-len(countyname)) + '(' + statename + ')'... 	0.000544334349305944
4968534	34041	sql distinct query	select id, moduleid, modulename, totalamount, category from tbl where id in  ( select min(id) from tbl group by moduleid ) 	0.367273461457552
4971990	381	php / mysql query. select either the one or the other	select * from matches where compo_id = '1'   and match_id < '5'   and (clan_user_id_1 = '0' or clan_user_id_2 = '0') 	0.00626552155773855
4976002	6067	mysql multi-table join on ids	select c.*,           ifnull(ifnull(p.content, t.content), l.content) as content,           t.title,           l.desc,           l.link,           p.hash      from post_contoller c left join post_text t on t.id = c.id left join post_photo p on p.id = c.id left join post_link l on l.id = c.id 	0.129724594955302
4978614	3185	select from 2 tables	select   t1.name_transfer,    t2a.name_account as name_account_from,    t1.value_from,    t2b.name_account as  name_account_to,    t1.value_to from   table1 t1   inner join table2 t2a on t2a.id = t1.id_account_from   inner join table2 t2b on t2b.id = t1.id_account_to where   t1.id = 1 	0.00284561438446653
5007485	11488	sql query for most popular combination	select a.itemid, b.itemid, count(*) countforcombination from grocery_store a inner join grocery_store b on a.customer_id = b.customer_id and a.itemid < b.itemid group by a.itemid, b.itemid order by countforcombination desc 	0.0149743313505254
5011766	37037	how do you find out the total size of the data in mysql database?	select s.schema_name,  concat(ifnull(round((sum(t.data_length)+sum(t.index_length)) /1024/1024,2),0.00)) total_size_in_mb,  concat(ifnull(round(((sum(t.data_length)+sum(t.index_length))-sum(t.data_free))/1024/1024,2),0.00)) data_used_in_mb,  concat(ifnull(round(sum(data_free)/1024/1024,2),0.00)) data_free_in_mb,  ifnull(round((((sum(t.data_length)+sum(t.index_length))-sum(t.data_free))/((sum(t.data_length)+sum(t.index_length)))*100),2),0) pct_used,  count(table_name) total_tables  from information_schema.schemata s  left join information_schema.tables t on s.schema_name = t.table_schema  where s.schema_name = 'abc'  group by s.schema_name  order by pct_used desc; 	0
5020996	6055	string manipulation in sql server-- adding placeholder characters	select stuff(stuff(@p_mystringvariable,1,0,'m'),7,0,'m') 	0.725756895304985
5021078	29946	how to determine which rows in table are not properly sorted by parent table	select distinct parentid from  ( select *, rn=row_number() over (partition by parentid order by sortorder) -1 from child ) x where rn <> sortorder 	7.31082040915239e-05
5025556	22454	sql server - group records like archives by month	select count(id), datepart(year, dtcreated) as y, datepart(month,dtcreated) as mo      from taxessteps group by datepart(year, dtcreated), datepart(month,dtcreated)     order by 2 desc, 3 desc 	0.0841981377633771
5055562	22690	how to find destination ip address of a linked server in sql server 2008?	select * from openquery (          mylinkedserver,           'select              @@servername as targetservername,              suser_sname() as connectedwith,              db_name() as defaultdb,              client_net_address as ipaddress           from               sys.dm_exec_connections           where               session_id = @@spid         ') 	0.0851344837195098
5060102	38186	select only records which must fill two conditions	select a.* from table1 a     left join table1 b on b.otherid = a.otherid and b.type = 5 where a.type = 4 and b.id is null 	0
5063483	37613	do we have any inbuilt function which will tell me if this value present in the column	select * from mytable where instr(col2, 'a') > 0 select * from mytable where col2 like '%a%' 	0.50766293517033
5079711	16831	implementing a find-or-insert for one-to-many tables	select distinct tracklist     from track t0     where        (select count(distinct tracklist)         from track t1           where              (               (t1.id='test1.id')               or                (t1.id='test2.id')               ......               or                (t1.id='testn.id')             )       = 1); 	0.473829499573886
5079894	11375	mysql & regex: match the whole word only or skip urls?	select pg_id as id,  pg_url as url, pg_title as title, pg_content_1 as content_1, pg_content_2 as content_2, parent_id as parent_id, extract(day from pg_created) as date, extract(month from pg_created) as month, extract(year from pg_created) as year from root_pages where root_pages.pg_cat_id = '2' and root_pages.parent_id != root_pages.pg_id and root_pages.pg_hide != '1' and root_pages.pg_url != 'cms' and root_pages.pg_content_1 like '%".$search."%' or root_pages.pg_content_2 like '%".$search."%' and root_pages.pg_content_1 not like '%http: and root_pages.pg_content_2 not like '%http: order by root_pages.pg_created desc 	0.00587464965979175
5083422	35732	how do i select a specific id from a table, and at the same time find out how many rows there in total within just one query?	select t.*, (select count(*) from `table`) as total from `table` t where id='1' 	0
5083787	32661	sql server 2008 - only find inactive records	select  orders.orderid, orders.orderdate from    orders inner join         orderitems on orders.orderid = orderitems.orderid inner join         products on orderitems.productid = products.productid inner join         productsubcategories on products.productsubcategoryid = productsubcategories.productsubcategoryid inner join         productcategories on productsubcategories.productcategoryid = productcategories.productcategoryid where   (orders.customerid = @customerid) and (productsubcategories.productcategoryid = 1) group by    orders.orderid, orders.orderdate having min(orderitems.orderitemstatusid) = 2 	0.0127790540183383
5083953	30767	check dts package info	select * from msdb..sysssispackages 	0.0423094151062243
5086603	13973	sql server filestream total file size	select sum(datalength(filestreamcolumn)) from filestreamtable; 	0.0879160539919669
5092706	27483	how to count and group items by day of the week?	select  count(`tweet_id`), dayname(from_unixtime(created_at))) as day_name1 from tweets2  group by day_name1 order by day_name1; 	0
5105491	19326	how can i create a statistics tool with php/mysql from existing timestamps?	select hour( timestamp ) as the_hour, count(*) as entries  from your_table where date( timestamp ) = now() group by hour( timestamp ) 	0.000368752533442516
5105672	27730	for a multiline intersecting several polygons, get the respective lengths	select p.geo, p.id, p.geo.stintersection(l.geo).stlength() from polygons p, lines l where p.geo.stintersects(l.geo) = 1 and l.id = @lineid 	0.00763534224835141
5115013	41011	php query to retrieve text and/or image status updates from pals and self	select av.picture_thumb_url as avatar_pic, update_text, upd_pic.picture_thumb_url as update_pic from   wid_updates upd   left join pictures upd_pic on attached_picture_id = upd_pic.picture_id   left join pictures av on av.user_id = upd.user_id and av.type = 'main_avatar_large'   where     upd.user_id in (select if (p.user1_id == current_user_id, p.user2_id, p.user1_id) as pal_id from pals p where p.user1_id = current_user_id or p.user2_id = current_user_id)   or upd.user_id = current_user_id order by timestamp desc 	0.0190797170212313
5123372	3143	sql: grouping by column after sorting	select name, max(rank) as maxrank     from books     group by name 	0.0865031413553247
5147257	26223	compare between two dates	select course.course_name, due_dates.course_id, due_id from course inner join due_dates on course.course_id = due_dates.course_id where now() between start_date and end_date; 	0.000399623750621585
5153108	37736	how can i select the primary key columns from the table?	select column_name from information_schema.columns   where table_name = '<table_name>' and is_nullable = 'no' 	0
5159064	13067	sql: rows before and after given row	select     (select count(*) from saleslt.customer where customerid < 55) as rows_before,    (select count(*) from saleslt.customer where customerid > 55) as rows_after,    customerid, firstname from saleslt.customer where customerid = 55 	0.000190973148309801
5170865	30148	getting all records where particular column is empty in access	select * from table where nz(particularfield,'') = '' 	0.000490668967872078
5181698	35763	how do i retrieve results from mysql where a timestamp is between 11pm yesterday and 11pm today?	select * from table where create_date  between concat_ws(' ',curdate(),'23:00:00') - interval 1 day  and concat_ws(' ',curdate(),'23:00:00') 	0
5182164	3247	sql server default character encoding	select serverproperty('collation') 	0.409616032119249
5201749	28330	how to get matching rows from two tables in sql, without repeated calls from java	select table1.*, table2.* from table1   left join table2 on table2.id = table1.table2id   where table1.id = 123; 	0
5210167	7383	collapse sql rows	select demotable.* from demotable left join demotable as prev on prev.id = demotable.id - 1 where demotable.name != prev.name 	0.071036995712693
5210965	31993	sql select user grouped by ip and select all other users with the same ips in one table	select * from your_table where ip_address in (select ip_address                      from your_table                      where user_name = 'peter')     and user_name <> 'peter' 	0
5214064	21067	sql query for all pairs of elements that are only in different groups	select s1.subject,        s2.subject from   survey s1        join survey s2          on s1.subject < s2.subject group  by s1.subject,           s2.subject having count(case                when s1.groupid = s2.groupid then 1              end) = 0 	0
5248461	25452	what's the best way to store my datastructure in database?	select p.productid,         p.productname,         case           when cb.combinationid > 0 then cb.price           else p.price        end,         cb.combinationid  from   products p         left join specifications sp           on sp.productid = p.productid         left join specvalues spv           on spv.specid = sp.specid         left join combinationparts cbp           on cbp.specvalueid = spv.specvalueid         left join combinations cb           on cb.combinationid = cbp.combinationid  where  p.productid in ( 1, 2 )         and case               when cb.combinationid > 0 then cb.combinationid in ( -100, 1, 2 )               else 1 = 1             end 	0.472184675911115
5263652	2074	sql server: select based on the latest id in a many to n:m relationship	select  from comments as c     inner join (                 select                      commentid                     ,max(actionid) as actionid                 from commentjoinaction                 group by commentid             )as cja         on c.commentid = cja.commentid         inner join action as a             on cja.actionid = a.actionid 	0
5263876	23241	sql - as - table doesn't exist - 1146	select [s? or maybe p?].pid from swapping s inner join post p on p.postid=s.postid where s.mid = '2' order by date desc limit(0,1) 	0.706084417009483
5264323	16771	mysql last instance of in a group	select subscriber_id, max(photo_id) from user_photos group by subscriber_id 	0.000748679662777683
5264637	12350	how can i speed up queries that are looking for the root node of a transitive closure?	select * from (     select         max(case when distance <> 0 then 1 else 0 end)             over (partition by child_node_id) has_non_zero_distance         ,transitive_closure.*     from transitive_closure ) where distance = 0     and has_non_zero_distance = 0; 	0.412201872049124
5271043	23119	i would like a mysql query. all the fields which contain a capital letter	select *          from personal_urls          where cast(vanity_url  as binary) rlike '[a-z]'; 	0.0027907881146164
5285388	9845	mysql check if username and password matches in database	select hashedpassword from users where username=? 	0.189232291263224
5301907	28679	how to run queries on multiple linked servers efficiently?	select * from openquery(@servername,'select * from mydb.dbo.mytable'); 	0.17051958412417
5303359	18340	sql return only those of certain age	select * from users  where (date_format(dob, '%y') - $stryear) <= 3  and (date_format(dob, '%y') - $stryear) > 0 	0
5325686	22892	prevent duplicated usernames with non-case-sensitive behavior in php/mysql	select username from table where lower(username) = lower('$username') 	0.343747167986163
5330569	5569	how to break numbers in sql?	select stuff(stuff('235698752',6,0,' '),2,0,' ') 	0.0450422486532188
5343296	40151	select only distinct values from duplicate rows	select client, totala, case when number = 1 then totalb else null end totalb, case when number = 1 then item else null end item  from (     select *, row_number() over(partition by client order by client) number      from clients  ) a 	0
5356624	26614	sorting mysql results based on a modified column	select ... from yourtable order by substr(yourcolumn, 5) 	0.000525208131144266
5363416	24054	mysql multi count in one query	select count(a.user_id) as numusersperstatus,           (select count(b.user_id)              from your_table b          group by b.date) as numusersperdate     from your_table a group by a.status 	0.084792052717416
5369589	29739	mysql query, how to group and count in one row?	select     orders.orderid,     orders.title,      count(orders.orderid) - sum(`products`.`isgratis`) as "qt paid",      sum(`products`.`isgratis`) as "qt gratis"  where `orders`.`orderid` = `products-vs-orders`.`orderid`   and `products-vs-orders`.`productid` = `products`.`productid` group by `products`.`packid` 	0.00369008582739066
5380728	14312	sql trigger - replace system user with custom field	select @username =(select your_userid_columnname from inserted) 	0.738522711956211
5383351	26199	pull a random id from a mysql table that a particular user has not seen before	select p.*  from   problems p         left join records r           on r.user_id = 100              and r.p_id = p.p_id  where  p.p_id is null         and p.p_id >= rand() * (select max(p_id)                                 from   problems)  limit  1 	0
5389016	3238	sql query implement two count in one	select tc.catename,        count(case when u.ag_code!=0 then 1 end) agnt,        count(case when u.ag_code =0 then 1 end) dircus from table1 as u inner join table2 as tc on u.industry_id=tc.tempcatid  group by tc.tempcatid, tc.catename 	0.083904553441859
5395360	31714	efficiently get min,max, and summary data	select tt1.post_date as first_purchase_date,        tt1.tx_amount as first_purchase_amount,        tt2.post_date as last_purchase_date,        tt2.tx_amount as last_purchase_amount,        tg.pc as purchase_count,        tg.amount as total from (select card_number,min(post_date) as  mipd, max(post_date) as mxpd, count(*) as pc, sum(tx_amount) as amount from tx_table where tx_type = 'purchase' group by card_number) tg join tx_table tt1 on tg.card_number=tt1.card_number and tg.mipd=tt1.post_date join tx_table tt2 on tg.card_number=tt2.card_number and tg.mxpd=tt2.post_date where tx_type = 'purchase' 	0.0180356388867621
5396717	37434	joining 3 three tables	select      album_table.album_id,      album_table.album_name,      images_table.filename from album_table inner join images_table on images_table.album_id = album_table.album_id where album_table.user_id = uid order by images_table.date desc 	0.0237369470814382
5408009	10111	finding "duplicate" rows that differ in one column	select *   from sensors_log s1   inner join sensors_log s2     on (s2.date = s1.date and         s2.date_millis = s1.date_millis and         s2.eib_address = s1.eib_address)   where s1.value <> s2.value or         s1.log_id <> s2.log_id or         s1.orig_log_id <> s2.orig_log_id; 	0
5429427	28206	unusual form of join	select f.id fileid,            f.name filename,             p.id productid,            p.name productname       from productstable p inner join filestable f on find_in_set(f.id, p.fileids)        and f.deleted = 'n'      where p.deleted = 'n' 	0.322036347783318
5431942	35593	mysql select multiple rows, multi and/or	select count(*) as numrows from orders where (dispatched = 'no' and orderstatus = 'complete' and category = 'tosort')    or category = 'new'; 	0.0496229376898552
5432367	24504	how to calculate blocks of free time using start and end time?	select *  from slots  where ...    left join appointments      where appointments.id is null 	0.000179906224930369
5440293	33021	check different fields from an mysql statement in php	select *  from table  where (name = 'test' and        email = 'test@email.com')    or (name like '%{$search_text}%')    or (email like '%{$search_text}%') 	0.00432497681152555
5445438	32404	how to use inner join on the same detail table repeatedly	select     bags_tbl.id,     bags_tbl.a,     bags_tbl.b,     a.fruit as baga_fruit,     b.fruit as bagb_fruit from bags_tbl inner join fruit_tbl a on bags_tbl.baga = a.id inner join fruit_tbl b on bags_tbl.bagb = b.id 	0.0280248876824916
5463384	31612	sequentially number rows by keyed group in sql?	select     code,     row_number() over (partition by code order by name) - 1 as c_no,     name from     mytable 	0.00975892835170734
5464851	20534	how to determine if two users share some information without mutliple queries	select  g.*, guv.group_id is not null as is_member from    group_users gua join    group g on      g.id = gua.group_id left join         group_users guv on      guv.group_id = gua.group_id         and guv.user_id = $v where   gua.user_id = $a 	0.00014342747460282
5467336	14885	how to retrive 4 last chars for mysql database field?	select * from table where substring(field, -4) = '.png' 	0.000160739838651839
5468291	27583	grouping by non-database field	select some_fields, end - start as duration from table order by duration 	0.0602398027225031
5482704	6132	how can i compare different columns of different rows in the same mysql table (in php)?	select a.*,b.* from friends_requests a, friends_requests b  where a.requester = b.requestee 	0
5497909	1080	sorting sqlite items alphebetically regardless of case?	select distinct name from food order by lower(name) 	0.0292297430431722
5508741	30894	alternative to limit 1 to extract a date range plus first entry before and after?	select datetime, value from readingglucoseblood where datetime between '2011-01-21 00:00:00' and datetime('2011-01-21 00:00:00', '+24 hours')  union all select * from ( select datetime, value from readingglucoseblood where datetime < '2011-01-21 00:00:00' order by datetime desc limit 1 ) x union all select * from ( select datetime, value from readingglucoseblood where datetime > datetime('2011-01-21 00:00:00', '+24 hours') order by datetime asc limit 1 ) y order by datetime asc 	0
5509342	9043	how do i retrieve all tables in a database using sql in ms access?	select name from msysobjects where type=1 and flags=0 ; 	0.00436930495536775
5513340	5366	how to append “%” symbol?	select cast(@avg as varchar(5)) + '%' 	0.146825698572739
5515357	10639	how can i write a sql query with multiple counts for different group bys?	select  worker, account, date,         sum(task_completed = 'received') as received_count,         sum(task_completed = 'processed') as processed_count from    mytable group by         worker, account, date 	0.23079223757058
5517233	8797	ms access query: concatenating rows through a query	select t.columna   , getlist("select columnb from table1 as t1 where t1.columna = " & [t].[columna],"",", ") as columnbitems from table1 as t group by t.columna; 	0.244350079971837
5519978	18025	sql reports how to count number of records that match a certain criteria	select date     , sum( case when status = 1 then 1 else 0 end ) status1count     , sum( case when status = 2 then 1 else 0 end ) status2count     , sum( case when status = 3 then 1 else 0 end ) status3count from mytable group by date 	0
5525822	11532	ordering by match accuracy in t-sql using multiple where-like statements	select * from   mytable where  field like '%a%'         or field like '%b%'         or field like '%c' order  by case             when field like '%a%' then 1             else 0           end + case                   when field like '%b%' then 1                   else 0                 end + case                         when field like '%c%' then 1                         else 0                       end 	0.561039070857113
5564600	38290	join with where condition	select straight_join        peoplelist.member_id,       members.last_name,       members.first_name,  (etc with any other fields)       ms.status_id,       ms.description (etc with any other fields from member_status table)    from       ( select distinct m.member_id             from members m             where m.member_id = memberdesiredvariable         union select f.friend_id as member_id             from friends f             where f.member_id = memberdesiredvariable         union select f2.member_id             from friends f2             where f2.friend_id = memberdesiredvariable ) peoplelist       join members          on peoplelist.member_id = members.member_id       join member_status ms          on peoplelist.member_id = ms.member_id 	0.78508591922451
5566530	39151	sqlite to postgres (heroku) date/time	select extract(epoch from now() - posts.created_at); 	0.733712840830083
5567864	28042	postgres what information is stored for a connection	select usename,         application_name,         client_addr,         backend_start,        query_start,        current_query from pg_stat_activity 	0.669428203927649
5611126	4349	finding all polls that a specific user hasn't voted on yet	select *   from pools  where id not in (        select poolid          from votes         where userid = 142        ) 	0.000570755291526166
5611196	38103	group mysql subcategories and categories	select sc.title as subcat_title, c.title as cat_title      from subcategory as sc left join category as c        on c.id = sc.cid 	0.101167698288363
5615172	20444	mysql: limit by a percentage of the amount of records?	select* from    (     select list.*, @counter := @counter +1 as counter     from (select @counter:=0) as initvar, list     order by value desc    ) as x where counter <= (10/100 * @counter); order by value desc 	0
5631399	20478	how to get age in months using birthdate column by mysql query?	select * from [table]  where  birthdate&gt= date_sub(curdate(),interval 600 month) and  birthdate&lt= date_sub(curdate(),interval 400 month) 	0.000205662409944669
5633138	21109	mysql rand with condition	select id, name from table1 where `on` = 1 order by rand() limit 0,10; 	0.621872198456101
5635446	14725	how to check if there data range between 2 given dates?	select * from mytable where timecreated between cast('7/20/08 12:01:01' as datetime) and cast('7/20/09 12:01:01' as datetime) 	0
5637646	10055	count duplicate entries with a special condition in mysql	select link, count( distinct category_id ) sum_of_categories    from links_table    group by link 	0.0023410090688772
5652800	37983	merge multiple records into one row in a table	select salesagentid, salesagentname, sum(salesamount) as salesamount   into #aggsales   from sales  group by salesagentid, salesagentname; truncate table sales;     insert into sales select * from #aggsales; drop table #aggsales; 	0
5653381	17976	determine if many-to-many record combination exists	select a_id from a_b group by a_id having group_concat(b_id) = '1,3,5'; 	0.0125444798244811
5664103	8641	filter by count(*) ? - mysql	select name, count(*)     from mytable     group by name     having count(*) > 1 	0.166175605519996
5665299	35074	how to order by items based on data from two mysql tables?	select   a.name,   b.score,   concat(a.company, format(b.score * b.handicap, 0)) as sortfield from a,b where ... sort by sortfield 	0
5669907	38408	select two fields from single column based on value in second column	select pr1.value as longdescription, pr2.value as shortdescription  from product_attributes pr1  join product_attributes as pr2  where pr1.attribute_id=57 and pr2.attribute_id=58 	0
5676409	32137	how to format a mysql query that involves divison	select * from table where (cola / colb > 0.4) and (cola / colb < 0.6); 	0.513469151860652
5676790	4242	mysql - how can i select rows by year if i have only the timestamp?	select * from table where from_unixtime(timestamp, '%y') = 2011; 	0
5696599	35770	sql: how to get last items?	select log.document_id      , (unix_timestamp() - log.timestamp) / 60        as minutessincelastchange  from log   join     ( select document_id            , max(timestamp) as last_change       from log       group by document_id       having (last_change < (unix_timestamp() - 60 * 10))  <     ) as grp     on  grp.document_id = log.document_id     and grp.last_change = log.timestamp where log.status_code = "200"             < 	0
5703243	33618	mysql. sql query. selecting	select * from `table` group by title,artist; 	0.166640051458259
5719185	35425	sql relationships	select bl.userid, b.name, t.estimate from batch_log as bl join batches as b     on b.id = bl.batch_id join task as t     on t.id = b.task_id where bl.userid = 123 	0.295268339235976
5721040	4465	oracle/sql - combining counts from 'unrelated' unrelated tables	select (select count(*) as good          from   table_good          where  widget = 'widget a'                 and good = 'y') as good,         (select count(*) as bad          from   table_bad          where  widget = 'widget a'                 and bad = 'y')  as bad  from   dual 	0.000239678695720087
5725237	41165	sql query of using functions - how to get maximum count of the list	select customer_id,         count(customer_id) as customerrowcount  from   rental  group  by customer_id  having count(customer_id) = (select count(customer_id)                               from   rental                               group  by customer_id                               order  by count(customer_id) desc                               limit  1) 	0.000101683132240499
5734504	39595	mysql : left part of a string split by a separator string?	select substring_index(column_name, '==', 1) from table ; select substring_index(column_name, '==', -1) from table; 	0.0197725437109659
5763145	23201	how to extract the latest row	select *  from table as outertable where date = (select max(date) from table where serial_no = outertable.serial_no) 	0
5777698	14544	returning the most recent messages from mysql?	select      messages_threads.id as threadid, messages_threads.name as recipientsname,      senderid, username as sendername, pictures.url as senderpicture from      messages_recipients     join messages_threads on messages_threads.id = messages_recipients.threadid     join users on users.id = messages_threads.senderid     join pictures on messages_threads.senderid = pictures.userid and pictures.profile = 1     join ( select threadid, max(id) as postid from messages_message group by threadid ) t on message_threads.id = t.threadid     join messages_message on t.threadid = messages_message.threadid and t.postid = messages_message.id where messages_recipients.userid = $userid 	0.000125739305645719
5800448	29512	remove single quote from the column value in oracle sql	select replace (msgid, '''', '') from schemaname_interface_daily_20110427; 	0.000315338706533708
5801505	10331	how to check linked server in oracle?	select * from dba_db_links 	0.208789498711446
5804036	26877	count subscribers who have subscribed to all magazines(3 different magazines)	select count(*)    from (select sub_id, count(distinct mag_id)            from dvd_subscriptions           where mag_id in (1, 2, 3)           group by sub_id         having count(distinct mag_id) = 3) 	4.68752896447318e-05
5816065	40192	sql find similar rows without having all combination	select distinct    t1.code, t1.id, t1.description, t2.id, t2.description from    data t1, data t2   where    t1.code = t2.code and t1.id < t2.id order by t1.code 	0.000394874199991646
5820440	20872	sql: getting possible values for 'in' operator from two different tables	select *  from table1  where msgnum in  (  select table2.msgnum from table2 where systemid = 'sys-0001'   union  select table3.msgnum from table3 where incidentnumber = 'incident-0001' ) 	0.00100751760767878
5825230	10579	find the difference between two date fields that are within a certain time parameter	select count(*) from yourtable where datediff(minute,startdate,enddate) <= 30 and archived = 1 	0
5825804	37977	mysql: order by field, placing empty cells at end	select * from table order by if(field = '' or field is null,1,0),field 	0.00389398503418123
5838806	22646	sql: query one table based on join on another table that has multiple matches	select dog.*,        group_concat(dc_all.color) as colors from dog join dog_color as dc_white on (dog.id = dc_white.dog_id and dc_white.color = 'white') join dog_color as dc_black on (dog.id = dc_black.dog_id and dc_black.color = 'black') left join dog_color as dc_all on (dog.id = dc_all.dog_id); 	0
5852233	16520	search sql query from multiple tables mysql	select id,name,surname,position,'worker' as tbl from worker where .. union all select id,name,surname,'','customer' from customer where ... 	0.0634684343922936
5864380	34415	consolidate records	select id, referenceid from mytable where id in (                 select min( z.id ) as id                 from    (                         select z1.id, group_concat( z1.referenceid ) as signature                         from    (                                 select id, referenceid                                 from mytable                                 order by id, referenceid                                 ) as z1                         group by z1.id                         ) as z                 group by z.signature                 ) 	0.0215632702011928
5870022	17046	mysql self-refrencing table returning id of parent and count of children	select parent_id parent, count( * ) num_children from example group by parent_id having parent_id in ( select id from `example` where parent_id =0 ) 	0
5874367	12306	ms access average after subtracting	select col3, format(avg([col2]-[col1]),"hh:mm:ss") as timediff from table1 group by col3; 	0.0181165096952671
5887104	36734	grant privileges on several tables with specific prefix	select   concat('grant select on test.', table_name, ' to ''foouser'';') from     information_schema.tables where    table_schema = 'test'       and table_name like 'foo_%' 	0.115154418972885
5902389	10810	one query to select a record from table a that has both options in the relationship table b	select p.productid, p.name    from product as p   where 2 = (select count(*)                from product_option as po               inner                join option as o                  on po.optionid = o.optionid                 and po.productid = p.productid                 and o.name in ('value1', 'value2')); 	0
5920383	37852	sql server 2008 - how to join 3 tables	select users.name, scores.lessonid, scores.result, lessons.title from users inner join scores on users.studentid = scores.studentid inner join lessons on scores.lessonid = lessons.lessonid 	0.39482687410374
5921327	27339	selecting random entry from mysql database	select author, authortext, date from table order by rand() limit 1 	0.0001336818027329
5929510	1133	mysql query order the results in group by	select *, `last`.`user_id` as last_user_id from (     select users.user_id,            users.username,            topics.title,            topics.topic_id,           topics.previews,           topics.date_added,           posts.post_id,            max( posts.post_id ) as last_post_id,           posts.date_added as last_data          from `topics`     left join `users` on users.user_id = topics.user_id     left join `posts` on ( posts.topic_id = topics.topic_id )         where fcat_id = '2'      group by topics.topic_id  ) as `tst` left join `posts` on ( posts.post_id = tst.last_post_id ) left join `users` as `last` on ( `last`.user_id = posts.post_id ) 	0.27905642069683
5945777	5769	how to use sql to find second-highest auction bids	select top 1 * from (    select top 2 *    from table    where <criteria match>    order by amount desc ) as newtable order by amount asc 	0.632294445588836
5953592	41293	how to query access to select entire records given a distinct criteria	select     c.* from     customer  c      inner join      (     select          c.promo1,         min(c.autoid) autoid     from          customer  c     group by         c.promo1) firstcusomterwithpromo     on c.autoid = firstcusomterwithpromo.autoid 	5.5110137634656e-05
5958212	26841	mysql - "most social user" with the most comments in multiple tables	select x.posterid,           count(y.posterid) + count(z.posterid) as numcomments      from (select vc.posterid              from videocomments vc            union             select sc.posterid              from storycomments sc) x left join videocomments y on y.posterid = x.posterid left join storycomments z on z.posterid = x.posterid  group by x.posterid  order by numcomments desc     limit 1 	0.000446542179348165
5962007	33403	t-sql query self join via date table	select   today.date,   today.price,   yesterday.date,   yesterday.price,   today.pricetype from price today   inner join dates d on today.date = d.date   inner join price yesterday     on d.yesterdaydate = yesterday.date and today.pricetype = yesterday.pricetype 	0.587176814503777
5964730	39648	sqlserver 2008 - deleting rows containing terms found in a black list table	select    a.string from    a a    cross apply    (select b.term from blacklist b where contains(a.string, b.term)) foo 	0.00186339093430111
5968859	3233	count(col1) by partitioning col2 values in equidistant intervals	select sum(case when col2 between -100 and -75 then 1 else 0 end) as interval1,        sum(case when col2 between -74 and -50 then 1 else 0 end) as interval2,        ...        sum(case when col2 between 176 and 200 then 1 else 0 end) as interval12     from yourtable 	0.0206304249853382
5969877	9354	sql reports with bi studio (bids) , i want one entry per page	select c.categoryname,    c.categorydescription,    p.productname,    p.productprice,    p.productdescription,    p.productnumber from category c join product p on  	0.00344880521973765
5980580	27012	selecting data from table with join	select *  from sportjefit_user left outer join vriend on sportjefit_user.id=vriend.vriend2   where !(vriend1=48 or vriend2=48)    or (vfriend1 is null and vfriend2 is null); 	0.00338521008179132
5997636	28605	sql server datetime cast from varchar	select (some id), birthdate from dbo.yourtable where isdate(birthdate) = 0 	0.109584542754086
6010136	34190	mysql, how to repeat same line x times	select    iv.number as boxnr   ,ordernumber     ,article_description   ,article_size_description   ,concat(numberperbox,' pieces') as contents   ,numberordered from   customerorder   inner join (     select        numbers.number       ,customerorder.ordernumber       ,customerorder.numberperbox     from       numbers       inner join customerorder         on numbers.number between 1 and customerorder.numberordered / customerorder.numberperbox     where       customerorder.id = 1     ) as iv     on customerorder.ordernumber = iv.ordernumber 	6.68699927098941e-05
6015534	7514	find in which database the table is located	select table_name,table_schema from information_schema.tables where table_name = 'your_table' 	0.00413991524596608
6022714	21832	php: sql query (timestamp)	select * from table where timestamp_info < date_sub(now(), interval 1 day); 	0.19682004409056
6025979	24837	using a sub query in column list	select sum(case when datediff(day, modifieddate, getdate()) <= 7 then 1 else 0 end) as '7days', sum(case when datediff(day, modifieddate, getdate()) > 7 and datediff(day, modifieddate, getdate()) <= 14 then 1 else 0 end) as '14days', sum(case when datediff(day, modifieddate, getdate()) > 14 and ddatediff(day, modifieddate, getdate()) <= 28 then 1 else 0 end) as '28days' from sales.salesorderdetail 	0.145463427604812
6038351	36242	sqlite select data from multiple rows returned as one row	select     a.id,     coalesce(a.name,'') as "name-1",     coalesce((select b.name from emp b               where b.id = a.id              and b.rowid != a.rowid limit 1),'') as "name-2" from emp a  group by a.id 	0
6046260	11665	return multiple columns of data from a single column with different where statements	select     [datetime],     max(case when id='measure 1' then [values] end) as measure1,     max(case when id='measure 2' then [values] end) as measure2 from     [table] group by     [datetime] 	0
6046500	9230	mysql select aggregates from two tables	select   u.username,   px.testa,   px.testb,   px.testc,   py.testd,   py.teste from users u   left join (     select       userid,       max(case testid when 1 then datetaken else null end) as testa,       max(case testid when 2 then datetaken else null end) as testb,       max(case testid when 3 then datetaken else null end) as testc     from passesx     group by userid   ) px on u.userid = px.userid   left join (     select       userid,       max(case testid when 4 then datetaken else null end) as testd,       max(case testid when 5 then datetaken else null end) as teste,     from passesy     group by userid   ) py on u.userid = py.userid 	0.0112725624670056
6048949	25171	2 sql command combined?	select t.mod_id, m.mod_naam, m.mod_omschrijving, m.taal_id, m.user_id from toewijzing t left join model m on t.mod_id = m.mod_id where t.user_id = session["userid"] and t.toe_status = "ja" 	0.220004507543541
6050224	17610	join query on multiple rows to search in	select u.id  from wp_users as u inner join wp_usermeta as umf on u.id = umf.user_id  inner join wp_usermeta as uml on u.id = uml.user_id  where umf.meta_key = 'first_name'      and umf.meta_value = 'myfirstname'     and uml.meta_key = 'last_name'      and uml.meta_value = 'dijkstra' 	0.0687933446680328
6051745	33611	sql - constraints which effect only one of the values returned?	select sum(a) as suma,         sum(b) as sumb,         sum(case when b is not null then a end) as foo, 	0
6052113	20190	counting results of complex query	select  sum(if(orsm.teststatus="pass",1,0)) as pass_count, sum(if(orsm.teststatus="skip",1,0)) as skip_count, sum(if(orsm.teststatus="skip",1,0)) / count(*) as skip_pct,    sum(if(orsm.teststatus="pass",1,0)) / count(*) as pass_pct, sum(if(orsm.teststatus="fail",1,0)) / count(*) as fail_pct from mdro orsm, mdr mr, cmt cm, mmrprt mrt, mmtt mtt, mmuq mui, mmgt mgt, mmft mft where mr.cmtid = cm.id  and orsm.parentid = mr.id  and cm.identid = mui.id  ... all the rest of your ands ... 	0.370941721703262
6053188	21415	find all characters in a table column of mysql database?	select distinct regexp_split_to_table(yourfield, '') as letter from yourtable; 	0
6062159	18722	connecting to mysql using java on debian	select field from `table` 	0.480846374734211
6064687	24182	mysql select all rows from last month until (now() - 1 month), for comparative purposes	select    * from   yourtable t where   t.date >= date_add(last_day(date_sub(now(), interval 2 month)), interval 1 day) and   r.date <= date_sub(now(), interval 1 month) 	0
6067526	7953	how do i group a date field to get quarterly results in mysql?	select year(leaddate) as year, quarter(leaddate) as quarter, count(jobid) as jobcount   from jobs  where contactid = '19249'  group by year(leaddate), quarter(leaddate)  order by year(leaddate), quarter(leaddate) 	0.00232440869033026
6072614	12676	mysql - select the first item returned by group_concat	select       v2.veg,       v2.price    from       ( select v1.type, min( v1.price ) as minimumprice             from veggies v1             group by v1.type ) prequery       join veggies v2          on prequery.type = v2.type          and prequery.minimumprice = v2.price 	0.000709425460347948
6077980	13164	adding a percentage column to existing data in mysql	select  users.full_name         ,sum(total)         ,sum(case when service < 49 then total else 0 end) as productive         ,(round((sum(total)/sum(case when service < 49 then total else 0 end)) * 100)) as percent ... 	0.00295370354375674
6090680	6555	t-sql search on 'combined' column name	select  * from production.product where (name + ' ' + productnumber) like 'bearing ball ba-8327' 	0.0329427269797394
6102309	6657	how to get 2nd highest from table?	select * from `tablename` order by `marks` desc limit 1,1 	0
6105230	23142	mysql table join problem	select u.id, u.name, group_concat(n.nickname, ' ') as nickname from user u left join nickname n on u.id = n.user_id group by u.id, u.name 	0.778811979272497
6122618	1795	sql two foreign keys linked to one primary key of another table to pull field from that table	select s.name as locality, n.name as state from notification n inner join location s on n.fkstate=s.pklocation inner join location l on  n.fklocality=l.pklocation 	0
6130372	5740	using mysql_fetch_object	select firstname, email, password from users where email = 'test@test.com and password = 'test' and enabled = 1 	0.397420115909969
6162927	2435	select from column where value in a list or no such column	select * from lenders where state='fl' or state is null 	0.000339888965244159
6163104	19687	mysql how to group_concat a specific field?	select d.iditem,         d.idtag,        ifnull(stag.en,stag.se) stag,        group_concat(ifnull(svalue.en,svalue.se)) svalue   from itemdata d   join strings stag on idtag = stag.idstring   join strings svalue on idvalue = svalue.idstring  where d.iditem = 1  group by d.iditem, d.idtag, ifnull(stag.en,stag.se)  order by stag 	0.024355201570188
6164785	33207	ignore records while doing like	select description,        title,        hidden from paragraphs where (description like '%some search%' or title like '%some search%') and hidden = 0 	0.407931727958501
6169263	24955	mysql's 'create database if not exists' misbehaves when database has live connections	select exists(     select 1     from information_schema.schemata     where schema_name = 'mydatabasename' ) as e 	0.730701225622135
6195397	8005	mysql query help finding rank by id	select a.videoid,  (select count(*) from cb_video b   where a.videoid !=b.videoid   and (b.wins/b.loses) > (a.wins/a.loses))+1 as rank from cb_video a where a.videoid = 116 	0.16868182518159
6197042	1818	i need just the count of unique phone numbers in my mysql table. how do i do that?	select count(distinct column_name)  from table_name 	0.00039845100834648
6201719	38213	sql fetch all in a self-join construction	select s1.siteid as parentsiteid, s1.sitetype as parenttype, s1.sitename as parentname, s1.sitedomain as parentdomain,        s2.siteid as childsiteid,  s2.sitetype as childtype,  s2.sitename as childname,  s2.sitedomain as childdomain     from sites s1         inner join sitesites ss             on s1.siteid = ss.parentid         inner join sites s2             on ss.childid = s2.siteid 	0.04132822442188
6211116	27972	how to select rows which are evenly distributed on some column?	select y.c1, y.c2, y.c3       from       (       select c1, c2, c3.... from x limit 500 order by rand()       ) as y       where y.c2 in ( 'imp1', 'imp2', 'imp3')       limit 10 	9.0879413800488e-05
6215736	25887	why do php and mysql unix timestamps diverge on 1983-10-29?	select @@global.time_zone, @@session.time_zone; 	0.060443677212175
6217879	21672	select newest record of any group of records (ignoring records with one record)	select ot.*    from       ( select             customer_id,             max( date_added ) as lastorderdate,          from             ordertable          having              count(*) > 1          group by             customer_id ) prequery      join ordertable ot         on prequery.customer_id = ot.customer_id        and prequery.lastorderdate = ot.date_added 	0
6217978	22113	sql - regroup by subfield	select s.id, s.name, r.* from regions r left join regions s on s.id = r.sub_region order by(coalesce(s.id, r.id), r.id) 	0.36920956390673
6231275	33685	mysql sum time with ranges in different days	select sum(   unix_timestamp(     case when finishtime > '2011-06-03 23:59:59' then '2011-06-03 23:59:59'           else finishtime end   ) -    unix_timestamp(     case when starttime < '2011-06-03 00:00:00' then '2011-06-03 00:00:00'           else starttime end   ) ) as seconds from log  where finishtime >= '2011-06-03 00:00:00' and starttime  <= '2011-06-03 23:59:59' and finishtime > starttime 	0
6260862	35630	select from view | order by not working	select convert(varchar,[date],103) as [date]                       ,[vouchertype]                       ,[billno]                       ,[debit]                       ,[credit] from [accountsledger] order by [accountsledger].[date] 	0.726889384762654
6278101	19485	how to show the vertical data horizentally through sql	select  jid,wid,accountreference,oereference,invoicenumber from     (      select colname, data from yourtablename )  p  pivot  (      max(data) for colname      in ([jid],[wid],[accountreference],[oereference],[invoicenumber]) ) as pvt 	0.00374898121491909
6279002	36165	mysql how to do count(*) on a query with joins?	select count(reviews.review_id), reviews.review_id, reviews.reviewers_rating, reviews.reviewers_name,  reviews.review_date, reviews.pros, reviews.cons, products.product_name, products.slug, products.community_rating, products.number_of_votes, products.users_rating, products.thumb_link, categories.category_name_single from reviews left join products on reviews.product_id = products.product_id left join categories on products.category = categories.category_id where reviews.approved =1 group by reviews.review_id order by reviews.review_date desc 	0.449398801301325
6288810	38813	php / mysql checking data between tables with long query	select i.*,(select count(*) from _votes where i.id = image_id) as total_votes, (select count(*) from _votes where i.id = image_id and user_id = ?) as voted  from _images as i where i.approved = 1 	0.394659299462859
6289063	6974	how do i select a fixed number of elements around (before, and the remainder after) one specific element in a mysql table?	select * from table where id < x order by id desc limit 4; select * from table where id > x order by id asc limit 4; 	0
6296061	14481	mysql relational question. get results when m:n null	select username     from user u         inner join usergroup ug             on u.usergroup_usergroupid = ug.usergroupid          left join user_has_bar ub             on u.userid = ub.user_userid     where u.userage = 10         and u.location_locationid = 1         and ub.user_userid is null 	0.708928088396501
6296145	12519	equivelant of mysql limit in oracle.query includes several tables?	select *  from   (   select distinct uc.virtual_clip_id, uc.clip_id, uc.duration, uc.title,                     uc.thumbnail,uc.filename, uc.description, uc.block_id_start,                    uc.block_id_end, u.uname,uc.cdate, uc.ctime, uc.privacy_level, uc.user_id                  , row_number() over(order by uc.virtual_clip_id desc) rn   from       user_clips uc, users u, user_like ul   where         ul.user_id="+user_id+" and u.user_id=uc.user_id and          uc.virtual_clip_id=ul.virtual_clip_id and ul.like_status='1'  ) where rn between "+offset+" and 4 	0.0280516618608201
6297000	9635	combining the two queries and adding return to array	select image from product where product_id = '82' union select image from product_image where product_id = '82'; 	0.00208760470218
6314636	24507	not able to merge two columns in sql server while printing	select cast(classid as varchar(x)) + ' .' + cast(classsectionid as varchar(y))      as class from classsectionmaster order by class 	0.0165710331834949
6316823	13730	how can i make a query, selecting only categories which have products into it?	select * from categories where exists(   select null   from products   join subcategories on products.fksubcatid = subcategories.pksubcatid   where subcategories.fkcatid = categories.pkcatid   having count(*) > 2) 	0
6318778	5160	find maximum value for each row	select m.*,s.`date` from machines as m inner join ( select mid,`date` from statechange order by `date` desc) as s on m.mid = s.mid group by m.mid 	0
6326418	23779	mysql: how to use comma, single quote, and double quote as columns?	select `t1`.`foo's, "bar"` from `t1`; 	0.0276899604346298
6332172	16080	select a row used for group by	select id,         asset,        rate,        asset_count from (     select id,            asset,             rate,            rank() over (partition by asset order by rate desc) as rank_rate,            count(asset) over (partition by null) as asset_count     from test      where owner in (1, 2) ) t where rank_rate = 1 order by rate desc 	0.0426700976310972
6333529	28238	mysql: naming a field as madeupfield and performing a where on that field	select   concat(date(`starttime`),' ',hour(`starttime`),':',lpad(1*(minute(`starttime`) div 1),2,'0'),':00') as date from   `times` having      `date` in ('2011-06-05 11:00:00', '2011-06-05 12:00:00') 	0.0145191539152001
6341677	19574	sql server query	select    min(id), barid, fname, lname, sum(cola), sum(colb), sum(colc) from    temp group by    barid, fname, lname 	0.698580681859737
6341723	670	[mysql]optimizing report monthly summary	select   v.v_vehicleid,   round(avg(if(day(wp_datetime) = 1, wp.wp_speed, null)), 2) as avg1,   round(avg(if(day(wp_datetime) = 2, wp.wp_speed, null)), 2) as avg2,   round(avg(if(day(wp_datetime) = 3, wp.wp_speed, null)), 2) as avg3,   ...   round(max(if(day(wp_datetime) = 1, wp.wp_speed, null)), 2) as max1,   round(max(if(day(wp_datetime) = 2, wp.wp_speed, null)), 2) as max2,   round(max(if(day(wp_datetime) = 3, wp.wp_speed, null)), 2) as max3,   ... from vehicles v   join waypoints wp on wp.wp_vehicleid = v.v_vehicleid group by   wp.wp_vehicleid 	0.0553847524780282
6363228	38655	how do i return rows where there is more than one type?	select distinct user_id from table where typecode = 'typea' or typecode = 'typeb'     group by user_id, typecode having count(typecode) > 1 	0.00302144281364354
6383331	9572	join of many to many tables	select count(*) as news_count, t.* from tag t     left outer join news_tag nt         on t.id = nt.tag_id group by t.id 	0.0435531965800837
6387539	15396	mysql changing order depending on contents of a column	select data.*  from data inner join page on (data.pageid=page.pageid) where data.pageid=1 order by  if(page.orderbymethod='most recent data first', now()-datadate,    if(page.orderbymethod='most recent data last', datadate-now(), dataname) ); 	8.34823406020492e-05
6389679	32162	how can you conditionally add inner joins to a select statement?	select *  from tablea a  inner join tableb b on b.id = a.id where @category = 'all' union all select *  from tablea a  inner join tablec c on c.id = a.id   where @category = 'open' 	0.645009497370264
6390977	29827	mysql - search/select which is ordered by relevance?	select id, sum(relevance) as searchrelevance from( select id, 1 as relevance from cars where year = 2008 union all select id, 1 as relevance from cars where model='fiesta') as t group by id order by sum(relevance) desc 	0.100137511518182
6403680	1092	subquery to show all other categories one to many relationships	select b.bookid, b.author, b.title, group_concat(distinct c.categorydesc) from book as b inner join bookcategories as bc on b.bookid = bc.bookid inner join categories as c on bc.categoryid = c.categoryid where b.bookid in (select bc1.bookid     from bookcategories as bc1     inner join bookcategories as bc2 on bc1.bookid = bc2.bookid     where bc1.categoryid = 1 and bc2.categoryid = 2) group by b.bookid; 	0
6442031	33051	query result reversing	select * from (select * from msg order by id desc limit 10) as requiredlimit order by id asc 	0.375614049315968
6442568	21953	how do i get the member count using joins	select membertomship_startdate,            count(member_id) from       members  t1,                membertomshiptable t2,                membershipstatustypetable t3, where  t1.member_id=t2.member_id and             t2.mshipstatustype_id= t3.membershipstatustypetable  and             t2.membertomship_startdate> <specify the date here>  and             t3.membershipstatusname='completed' and group by   t2.membertomship_startdate 	0.01743502394381
6457576	3828	mysql join - three tables, returning null where empty	select phrase.phrase_id, phrase.string orig_phrase, code_value.code_value, translation.string as trans_phrase from phrase inner join  translation on (translation.phrase_id = phrase.phrase_id) left join code_value on (code_value.code_value=translation.language_cd) where code_value.code_class = 'language_cd'  order by orig_phrase; 	0.414051602832929
6458971	38874	constraint with non foreign key join in django	select * from tablea where id in (select id from tableb where year=2011) 	0.0131951524080046
6480505	38940	sql show only the top 2 comments for each actionid	select id,         actionid,         commentid from (    select id,            actionid,            commentid,            row_number() over (partition by actionid order by id) rn    from your_table ) t where rn <= 2 	0
6483788	40611	multi-calculation query	select        p.name,       salessummary.productid,       coalesce( salessummary.totalsales, 0 ) totalsales        coalesce( salessummary.affsales, 0 ) affsales        coalesce( salessummary.refunds, 0 ) refunds     from       product p          left join             ( select s.productid,                     count(*) totalsales                      sum( if( s.affiliateid > 0, 1, 0 )) affsales,                     sum( if( ifnull( s.refundid, 0 ) > 0, 1, 0 )) refunds                  from                      sales s                  where                     s.paymentstatus = 'completed'                  group by                     s.productid             ) salessummary          on p.id = salessummary.productid 	0.46185082725027
6485609	35147	tsql to select the last 10 rows from a table?	select top(10) [datadate] from yourtable order by [datadate] desc 	0
6497343	33405	sql server schema output	select * from information_schema.tables; 	0.730448918016343
6538851	29861	sql scheduled job query, duration of last runs?	select     j.name,     h.run_status,     durationhhmmss = stuff(stuff(replace(str(h.run_duration,7,0),         ' ','0'),4,0,':'),7,0,':'),     [start_date] = convert(datetime, rtrim(run_date) + ' '         + stuff(stuff(replace(str(rtrim(h.run_time),6,0),         ' ','0'),3,0,':'),6,0,':')) from     msdb.dbo.sysjobs as j inner join     (         select job_id, instance_id = max(instance_id)             from msdb.dbo.sysjobhistory             group by job_id     ) as l     on j.job_id = l.job_id inner join     msdb.dbo.sysjobhistory as h     on h.job_id = l.job_id     and h.instance_id = l.instance_id order by     convert(int, h.run_duration) desc,     [start_date] desc; 	0.0608531179139521
6539556	27200	how to get only one of the rows that are diferent?	select newsletter_id, count(email) from newsletter_queue  group by newsletter_id 	0
6546090	27809	mysql where statement for finding expiry date within 2 days	select * from table where expiry between(today(), today() + 2) 	0.000269027827787302
6552412	7192	mysql - reshuffling data returned, set field value as new column	select      fielda as fielda,     sum(if(fieldb='cca', fieldc, 0)) as cca,     sum(if(fieldb='dde', fieldc, 0)) as dde     from mydata     group by fielda     order by fielda; 	0.00016217793919426
6570021	9967	trying to get the money members from table	select    member.lastname,   member.firstname   membershipstatustype.memberstatustype_name   membershiptype.membershiptype_name   memberstomships.membertomship_lastdate from    member   inner join memberstomships on member .member_id = memberstomships.memberid   inner join membershipstatustype on memberstomships.membershipstatusid = membershipstatustype.membershipstatusid    inner join membershiptype on membershipstatustype.membershiptype_name = membershiptype.membershiptype_name  where   ucase(memberstomships.membertomship_paymentmethod) = 'money' 	0.000149133953144811
6599011	4195	sql to gather data from one table while counting records in another	select jos_mfs_users.*,      (select count(jos_mfs_songs.id)          from jos_mfs_songs         where jos_mfs_songs.artist=jos_mfs_users.id) as song_count  from jos_mfs_users  where (select count(jos_mfs_songs.id)          from jos_mfs_songs         where jos_mfs_songs.artist=jos_mfs_users.id) > 10 	0
6599922	20481	query to get the monthly amount using mysql	select           member_id,           30*membership_total_amount/datediff(membership_enddate, membership_startdate) as monthly_amount      from          member 	0.000527104466430616
6602545	14658	how do i store intermediate data and share it between sql queries? 	select field1,field2,...fieldn into #tmp from sourcetable 	0.272366010471163
6603898	36449	dealing with conditionally-executed select statements	select top(coalesce(case @getall when 1 then 2000000000 end, @count, 15))   col1, col2 from ... 	0.752359118512668
6609315	40485	sql get the value above(larger) and below(smaller) of an inbetween value in a select statement	select 'max', max(thickness) value from thicknesses where thickness < requirement  union select 'min', min(thickness) value from thicknesses where thickness > requirement 	0.000724741009657858
6622951	33669	mysql using distinct on 2 fields only	select    m1.* from    messages m1  join    (select uid, touid, max(time) time from messages group by uid, touid) m2  on m1.uid=m2.uid and m1.touid=m2.touid and m1.time=m2.time where    m1.uid = "'.$currentuser.'" order by   m1.time desc; 	0.00162573149460314
6627218	15291	mysql: `select`` statement with `or` and `and`	select * from `donor` where  (`col1` like '%test%' or  `col2` like '%test%' or  `col3` like '%test%' or  `col4` like '%test%') and `delete` =0 	0.75996124760228
6628489	20639	mysql: merge three tables together	select t1.user, t2.tid, t2.name, t3.type, t1.mid from t1 right join t2 on t1.mid = t2.mid left join t3 on t2.tid = t3.tid; 	0.0198681310030549
6637029	31754	tsql - query to get count of items associated to each category and subcategory	select  c.categoryid ,       c.parentid ,       c.text ,       count(distinct i.itemid) from    categories c left join         categories c2 on      c.categoryid = c2.parentid left join             items i on      i.categoryid = c.categoryid         or i.categoryid = c2.categoryid group by         c.categoryid ,       c.parentid ,       c.text 	0
6642429	35687	display sql table bottom to up	select * from tablename order by columnname desc 	0.0013031128544554
6645988	16767	sql: sort from two tables and order by date	select null as col1, name as col2, added as col3 from a union all  select userid as col1, username as col2, created as col3 from b order by 3 	0.000526519285623767
6650480	20189	getting three random dates from each hour	select * from (     select *     from yourtable     order by rand() ) group by date(yourdate), hour(yourdate), floor(rand()*3) 	0
6675822	30489	select fields from different tables in sql without a need of matching fields	select mytable.mytable_id, yourtable.bar from mytable, yourtable order by rand() limit 2 	0
6684420	30565	sql do not return column if value is zero	select type, sum from ( select                        sum(case when status = 'r' then 1 else 0 end) as ready,                sum(case when status = 'p' then 1 else 0 end) as processing,                 sum(case when status = 'c' then 1 else 0 end) as complete,                sum(case when status = 'f' then 1 else 0 end) as failed,                sum(case when status = 'e' then 1 else 0 end) as error  from  maildefinition  ) a unpivot (      sum for type in ([ready],[processing],[complete],[failed],[error]) ) u where sum>0 	0.0176014125840508
6686564	2769	mysql: group by on all values except 0 and null?	select sum(`tid` is null) as `total_null`,        sum(`tid` = 0) as `total_zero`,         count(distinct `tid`) as `other`   from `mark_list`  where `user_id` = $userid 	0.00238879414140596
6686722	33008	oracle how to add generated column to a select *	select (col4 * (col1+col2+col3) + 13) as gen1, table1.*   from table1   where col3 > 123     and col4 = 5   order by col1, col2 	0.0418308217366051
6697686	20544	sorting some rows by average with sql	select     t.id,     t.group from     some_table t left outer join (     select         group,         '1970-01-01' +             interval avg(datediff('1970-01-01', birthdate)) day as avg_birthdate     from         some_table t2     group by         group     ) sq on sq.group = t.group order by     coalesce(sq.avg_birthdate, t.birthdate),     t.group 	0.00364807010766391
6701491	20706	mysql select distinct but limit the distinct values	select id, columnx from table as t1 join (     select distinct(columnx) as columnx     limit 1 ) as t2 on (t1.columnx = t2.columnx); 	0.0037083088642918
6709747	22986	mysql query - using sum of count	select count(count) from (select count(source) as count from call_details group by source having count > 1) as a 	0.110251935702307
6714848	30692	select extended property from sql server tables	select p.*, t.* from sys.extended_properties p inner join sys.tables t on p.major_id = t.object_id where class = 1 	0.0267550839012392
6720531	40900	select case/join when no rows	select a.town, b.country from towncountry a,  (select code, country from refdata b union select '' as code, 'not found' as country from refdata c), towncountry c where a.record=1 and b.code=c.countrycode and c.record=2 	0.0245137312535927
6733153	2951	select same column for 2 tables	select table1.id1, null as id2, table1.lastmodif_date from table1 union all select null, table2.id2, table2.lastmodif_date from table2 	0.000527143629228232
6747687	30765	oracle: return the result set from a cte from a inline table function	select t_interval(interval_get_udf(trunc(starttime) + rownum/24 , 1)) bulk collect into intervallist from dual  connect by level <= 65536 	0.0187208706447384
6755627	20974	mysql compare two tables	select count(*) from accounts left join members on accounts.id = members.id where status = 5 and account_access = 1 	0.00419854547811881
6769003	11749	determine length of sql server 2005 xml data returned	select datalength (                     (select *                     from products                     for xml raw, root('products')                     )                  ) 	0.0353536204576296
6770908	19264	get datetime with time as 23:59:59	select dateadd(ms, -3, '2011-07-20') 	0.011341310350151
6781103	2006	multiple rows to one row query	select userid, username, fname, group_concat(stratnames separator ', ') as strats from users u left join userstostrategy uts on uts.userid = u.userid left join strategy s on uts.stratid  = s.stratid   group by userid, username, fname 	0.000517182776890337
6789214	12103	get last sql query for all open connections	select    * from    sys.dm_exec_requests er    cross apply    sys.dm_exec_sql_text(er.sql_handle) as t 	5.59099132311394e-05
6794693	18040	add a string to sql select	select city   from (     select city     from mycities     union select '<<all>>'   ) x   order by city; 	0.0332590364110448
6801452	21032	retrieve right year in sql	select    distinct yr  from    nobel  where    yr not in (select yr from nobel where subject in ('chemistry')) and    subject in ('physics') 	0.0177453093715129
6805848	12085	sql - if table entry exists then	select *,    sum(acc.gold_coins + if(shop.gold_coins is null, 0, shop.gold_coins)) as total_gold from accounts as acc left join player_shops as shop on acc.acc_id = shop.acc_id group by acc.acc_id order by total_gold desc limit 100 	0.00406000931139944
6813504	18284	conditional group by result	select name,max(is_new) as is_new from <table> group by name 	0.618313064485992
6813869	14460	group by problem - need to get most recent rows for unique column combinations	select s.name, s.type, s.score from (     select name, type, max(date) as maxdate     from scores     group by name, type ) m inner join scores s on m.name = s.name and m.type = s.type and m.maxdate = s.date 	0
6820713	22094	mysql .net connector - get table that column belongs to?	select   table1.column1 as foo,  table2.column1 as bar,  ... 	0.00875561524784713
6863785	24084	select least row per group in sql	select top 1 sale_price, sale_id, condition from sales where sale_price in (select min(sale_price)                       from sales                       where                       expires_datetime > now()                       and                         item_id in                               (select item_id from items where isbn = 9780077225957)                       group by condition ) 	0.000755927871700486
6870504	29338	pick records since last particular day of week	select * from table     where       date_column > date_sub( now(), interval dayofweek(now()) + 3 day); 	0
6879391	22498	mysql join with limit 1 on joined table	select c.*,       (select p.id, p.title         from products as p        where p.category_id = c.id        limit 1) from categories c 	0.0474990073553084
6881903	21458	how to get query data using result from another query?	select   books.*,   shopping_cart.book_id,   shopping_cart.title,   sum(shopping_cart.quantity) as total_sales from   shopping_cart inner join   books on   shopping_cart.book_id = books.id group by   shopping_cart.title order by   total_sales desc 	0.00050091938777784
6910008	27980	mysql query to find the blank word by comparing 2 sentences	select reverse(          substr(            reverse(substr(field1 from instr(field2, '_')))          from            instr(reverse(field2), '_'))        ) from table 	0.00254107440982385
6910727	1391	like contains %	select * from table where colname like '%100[%]%' 	0.798766095326191
6912336	27179	mysql join multiple joins on the same table?	select people.first_name as "first name", people.last_name as "last name",  countries1.name as "country1", territories1.name as "territory1", cities1.name as "city1",  countries2.name as "country2", territories2.name as "territory2", cities2.name as "city2" from adb_people as people join root_cities as cities1 on people.city1 = cities1.id   and people.city2 = cities1.id join root_territories as territories1 on people.prov_state1 = territories1.id   and people.prov_state2 = territories1.id join root_countries as countries1 on people.country1 = countries1.id join root_cities as cities2 on people.city2 = cities2.id   and people.city2 = cities2.id join root_territories as territories2 on people.prov_state2 = territories2.id   and people.prov_state2 = territories2.id join root_countries as countries2 on people.country2 = countries2.id 	0.0215561204067126
6932428	32215	mysql select only where timestamp is from last 10 days	select * from comments where (city = '$city2') and (`date` > date_sub(now(), interval 10 day)); 	0
6932621	41135	how do i select single row in a group based upon date?	select * from tb  join (         select tb.item,          max(tb.effdate) effdate         from tb         where tb.effdate <= currentdate         group by tb.item     ) tmp      on tb.item = tmp.item     and tb.effdate = tmp.effdate 	0
6938085	3267	select using dynamically generated tablename	select foreign_table_id, foreign_table_name from `geo_table` gt where      case gt.foreign_table_name         when 'table1' then              exists (                 select * from table1                 where id = gt.foreign_table_id             )         when 'table2' then              exists (                 select * from table2                 where id = gt.foreign_table_id             )         else             false     end 	0.153389416512959
6942481	25896	query same thing in multiple columns?	select p2 as partner, score     from table     where p1 = 'sinan' union all select p1 as partner, score     from table     where p2 = 'sinan' 	0.0172451999380728
6945233	31507	sql select dates in future and not ending before until date	select * from shows s  where s.show_status = 'enabled' and  (   s.show_from >= current_date()    or (s.show_from <= current_date() and s.show_until >= current_date()) ) order by s.show_from asc 	0.000689798475784641
6946636	25853	mysql: adding and multiplying on different tables	select sum(first_table.link_id * second_table.factor) as answer from   first_table left join second_table on first_table.link_id = second_table.id where  first_table.counted = 1 	0.00254330983926155
6947885	10137	used joined tables in select statment	select   m.mid,    [count] = case count(*) over (partition by r.refundid)     when 1 then 'one'     else 'many'   end from #temp t join refund r on r.refundid = t.refundid 	0.14664103071254
6949672	15313	sql query to find previous records	select trandate, location, badrec from     (     select pr.trandate, pr.location, pr.badrec,         row_number() over (partition by r.trandate order by pr.trandate desc) as sequence     from records r     join records pr on r.location = pr.location                     and r.trandate >= pr.trandate     where r.badrec = 1     ) x where sequence <= 4 	0.00114901101560209
6951595	32505	trying to call mysql procedure to return int value based on condition to php	select confirmmember($username,$password) 	0.00305599916230592
6963545	8186	group by columns + count(*), how to get the average count for every combination?	select resolvedby, [count], ficategory, fisubcategory, fisymptom     , avg(z.count) over( partition by ficategory, fisubcategory, fisymptom ) as avgbygrp from    (         select resolvedby, count(*) as [count], ficategory, fisubcategory, fisymptom         from tcontact          group by resolvedby, ficategory, fisubcategory, fisymptom         ) as z order by z.count desc 	0
6968651	36424	find first row per year that meets criterion in mysql table	select min(s.gamenumber),s.year,s.month,s.day,s.homeaway from stats s where s.homeaway='h' group by s.year 	0
6969861	5288	joining separate columns from one table in select statement	select playername, n.nationality, p.country from tbl_soccer_player join tbl_nationality as n on tbl_soccer_player.nationalityid = n.nationalityid join tbl_nationality as p on tbl_soccer_player.playsforid = p.nationalityid 	5.38572123064788e-05
6977688	11241	is there any way to get the offset of the record in the mysql resultset ?	select @rownum:=@rownum+1 ‘rank’, t.*     from my_table t, (select @rownum:=0) r order by field2; 	0.000606942817301423
6985178	3601	how to select from mysql where a set does not equal a value?	select *, find_in_set('hidden', props) as hidden from gt_content having hidden is null 	0.0104622758445539
6986386	32446	how to make null equal null in oracle	select  count(1)   from    tablea where    wrap_up_cd = val   and ((brn_brand_id = filter) or (brn_brand_id is null and filter is null)) 	0.381538114029951
6988503	7314	mysql regexp no whitespaces no numbers	select * from table_name where cola not regexp '[0-9[:space:]]' and colb not regexp '[0-9[:space:]]' 	0.0883656398790043
6999837	16904	joining mysql queries problem	select distinct      o.room, o.date,o.module_code,o.observer_id,o.staff_id,o.form_id,     s1.name, s2.name from      mbm2_db.observation_details as o     left join mbm2_db.staff as s1 on o.observer_id = s1.staff_id     left join mbm2_db.staff as s2 on o.staff_id = s2.staff_id where      o.date = '2011-08-09' and o.module_code = 'is5103' 	0.789990278641087
7008887	15873	duplication caused by join	select users.userid from users     left join bind_groups on users.userid = bind_groups.userid     where groupid = 26 or groupid = 87 group by userid 	0.765822480682681
7024115	28406	ansi sql relationships produce duplicate records on query, distinct does not work, any other solutions available?	select                      traders.name as tradername,                     worksorders.id as worksorderno,                     worksorders.partid,                     worksorders.quantity,                     worksorders.duedate,                     worksorders.traderid,                     worksorders.orderid                 from worksorders                     inner join traders traders on                         worksorders.traderid = traders.id 	0.43876311038639
7026967	3078	unpivoting data from spreadsheet into data tables	select pk_2, "g1" as "pk_1", g1 as [value] from table union select pk_2, "g2" as "pk_1", g2 as [value] from table 	0.00121752788689135
7054883	24288	sql statement to find last word in string	select substring_index(col1, ' ', -1) from table 	0.00078221569288686
7063293	326	if clause in sql from statement	select userreturnval, userregisterid, othervalue from (    (select othervalue    from...    ) as tblo     ,   (      select userreturnval, userregisterid     from     (      select userreturnval, userregisterid, rank() over (partition by .. order by       ...) as rank             from ...             where                  case                      when (select count(userregisterid) from table1 where site =@siteid and userid=@userid) >0 then                          case when then 1                         else 0                         end                     else                         case when then 1                         else 0                         end                     end                  = 1                         ) as tblrank         where (rank =1)   ) as tblr 	0.566120942871742
7068215	28350	how to compare date range in a varchar coloumn	select startdate, isdate(startdate)  from mytable  where startdate is not null   and isdate(startdate) = 0 	0.000161822947463803
7072455	14634	returning rows as columns	select p.name, p.partnum, p.sku,        max( case when s.name='weight' then s.value else null end ) weight,        max( case when s.name='height' then s.value else null end ) height,        max( case when s.name='color'  then s.value else null end ) color from product p join product_spec s on p.id = s.p_id where sku <= 1003 group by p.name, p.partnum, p.sku 	0.00708287088862498
7072911	2547	how do i select current program from this table	select program from programs  where curdate() = p_day    and curtime() between p_start and p_end; 	0.0123229887969613
7081034	24788	sql statement that will take 70 or so rows from multiple tables and pivot them to columns	select   zn, cu, mn, se,   [rt-æg] as rt,   [bc-æg] as bc,   atmg, [d-iu], vitc,   thia, ribo, mg,   pant, b6, fola,   b12, vitk, foac,   chol, trfa, tsat,   mufa, pufa, star,   tomega3, tomega6,   prot, fat, carb,   kcal, tsug, tdf,   ca, fe, p, k, na from (   select u.nutrientvalue, n.nutrientsymbol   from user_amount u inner join nutrient n on n.nutrientid = u.nutrientid   where u.userid = 1 ) t pivot (   max(nutrientvalue) for nutrientsymbol in (     zn, cu, mn, se,     [rt-æg], [bc-æg],     atmg, [d-iu], vitc,     thia, ribo, mg,     pant, b6, fola,     b12, vitk, foac,     chol, trfa, tsat,     mufa, pufa, star,     tomega3, tomega6,     prot, fat, carb,     kcal, tsug, tdf,     ca, fe, p, k, na) ) x; 	0.000324032482896647
7083601	1228	how to get rows which have a date that's either today or was yesterday or the day before in mysql?	select * from `datestable`     where (         month(`thedate`) = month(curdate())         and day(`thedate`) = day(curdate())     ) or (         month(`thedate`) = month(date_add(curdate(), interval -1 day))         and day(`thedate`) = day(date_add(curdate(), interval -1 day))     ) or (         month(`thedate`) = month(date_add(curdate(), interval -2 day))         and day(`thedate`) = day(date_add(curdate(), interval -2 day))     ) 	0
7084177	29020	how to produce a distinct count of records that are stored by day by month	select        (year(ticketdate) * 100) + month(ticketdate),    count(*) as dailyticketcount from    nat_jobline group by  (year(ticketdate) * 100) + month(ticketdate) 	0
7086458	28888	mysql search text column for a specific word	select * from my_table where description like ='%test%' 	0.0129902470768366
7089410	4757	how to optimize oracle query from partitioned table?	select * from table t where t.fdate between to_date('1.6.2011', 'dd.mm.yyyy') and to_date('30.6.2011', 'dd.mm.yyyy'); 	0.263327556385394
7097151	22221	beginner - query a value in a column that's labeled as text	select `id`, `keyword_netword_id`, `text`, `match_type`, `create_date` from `keywords` where `text` like '%medicare supplemental insurance%'; 	0.154260288901244
7099251	37866	mysql "every row excluded, but only once" join	select boyunmatched.id  as aid      , null             as b_id         , girlunmatched.id as bid       , null             as a_id    from     ( select @rownuma := @rownuma+1 as rank            , id        from a          , (select @rownuma :=0) as dummy       where b_id is null       order by id     ) as boyunmatched   join     ( select @rownumb := @rownumb+1 as rank            , id        from b          , (select @rownumb :=0) as dummy       where a_id is null       order by id     ) as girlunmatched   on boyunmatched.rank = girlunmatched.rank 	0.000131246106360056
7101212	6074	mysql statement to quickly select group from n:n table	select programmer from ( select distinct programmer, language        from speaks_table        where language in ('c++', 'python') ) as disjunction group by disjunction.programmer having count(disjunction.language) = 2 	0.0968655931565593
7116508	17902	don't want the excess tag in my for xml path('td')	select empid "td/@id", empno "td"  from employees  for xml path('') 	0.0942011032810555
7123095	1833	mysql: combining two repetitive queries	select *  from root_documents  where (root_documents.pg_id = ? or (root_documents.pg_id is null and ? is null)) 	0.11931874037746
7130655	28772	mysql: order by joined table column	select      u.*,     ur.friend_id,     count(         if(um.to_user_id = ?,             (if(um.`date` >= ulr.last_read,um.message_id,null))         ,null)     ) as new_messages,     (         select t_1          from images          where ad_id = a.id          order by t_1 desc          limit 1     ) as user_photo from      user_relationships ur     left join `user` u on u.user_id=ur.friend_id     left join user_messages um on um.from_user_id=ur.friend_id     left join user_last_read ulr on ulr.read_who=ur.friend_id     left join ads a on a.user_id=u.user_id where ur.user_id=? group by ur.friend_id order by new_messages desc 	0.0114161683025032
7140983	6151	mysql and mybatis select distinct rows where value <= ##	select u.username, u.firstname, u.lastname, min(r.rolelevel) minrolelevel   from authorities a, roles r, users u  where r.role =  a.authority    and a.username = u.username     and r.rolelevel <= #{rolelevel}  group by u.username, u.firstname, u.lastname   order by u.lastname, u.firstname 	0.0529808929424964
7145694	4044	pivot with month()	select     def_kstnr,     [1] as jan,     [2] as feb,     [3] as mrz,     [4] as apr,     [5] as mai,     [6] as jun,     [7] as jul,     [8] as aug,     [9] as sep,     [10] as okt,     [11] as nov,     [12] as dez from (select  def_kstnr, def_zeit,  month(def_datum) as tmonth   from     dbo.def) source pivot (     sum(def_zeit)     for tmonth     in ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] ) ) as pvtmonth 	0.0708033055323776
7150546	31172	filtering by renamed column in mysql	select l from  (     select       ifnull(char_length(fiedl1), 0) +      ifnull(char_length(fiedl2), 0) +      ifnull(char_length(fiedl3), 0) +      ifnull(char_length(fiedl4), 0) +      ifnull(char_length(fiedl5), 0) +      ifnull(char_length(fiedl6), 0) as l      from mytable )  as r where l < 100; 	0.110194946053697
7150959	19206	what are the ramifications of having a ton of views in mysql	select * from vwmytentants where tenantid = 30 	0.0163809457606419
7173589	11229	mysql variables	select a.* from animals a left join foods f   on a.foodtype = f.idfood order by a.`food consumption` * f.price; 	0.409620878955346
7178146	27011	mysql retrieve column names where datatype == x	select     table_name,     column_name from     information_schema.columns where     table_schema = 'db-name' and     data_type = 'decimal' and     numeric_precision = 12 and     numeric_scale = 5 	0.000205699970916785
7180369	7647	multiple table join issue	select a.id, a.name,         c.name as category,         group_concat(subcat.name) as subcategories from accounts as a inner join account_has_subcategory as ahs on a.id = ahs.account_id inner join subcategory as subcat on subcat.id = ahs.subcat_id inner join category as c on a.category = c.id group by a.id, a.name, c.name order by a.id; 	0.777672607249212
7183378	15214	mysql query question on count	select if((sum(vote=1)-sum(vote=0) > 0,1,count(groupid)) from sample where uid = $uid group by groupid 	0.753338269801881
7194640	12785	mssql changing a return value only if it pass a boolean_expression	select    case t.endtime       when '00:00:00' then '23:59:59'       else t.endtime    end from ... 	0.00391252027487424
7206310	11169	need to get a count on a mysql join query	select count(entries.id)  .... 	0.0787496939411569
7208127	821	the minimum row on a join	select      a.id,      a.name as namea,     b.name as nameb, from tablea as a left join tableb as b     on b.refid=a.id and b.position = (select min(position) from tableb b2 where b2.rf_id = a.id) 	0.0021916131573368
7219385	33076	how to join only one column?	select table1.*, table2.first_name      from table1 left join table2 ... 	0.00237276998060518
7219875	1094	mysql query, select all clients and their orders	select customers.name, count(orders.id)  from customers  left join orders on customers.id=orders.customer_id  group by customers.name 	0.000187368697525947
7222565	16474	selecting available timeslots for a specific date	select *  from `timeslots`  left join schedule on timeslots.timeslot_id = schedule.schedule_timeslot where  schedule.schedule_id is null or schedule.schedule_date <> '2011-08-01' limit 0, 30 	0.000177552614354322
7228188	6475	control flow with if in mysql request	select id_customer, email, firstname, lastname, birthday,  if(newsletter=1, "abonné", "non abonné") is_subscribed  from "._db_prefix_."customer order by lastname asc 	0.788148853704537
7230534	12927	mysql - how to query items by tags, order by matched tag count	select *, count(*) as tag_count ..... 	0.000833075540007866
7235685	12521	how to determine if the sql server supports replication	select name, case when is_published = 1 or is_merge_published = 1 or is_distributor = 1 then 1 else 0 end as uses_replication from sys.databases 	0.220022581137398
7237596	24813	manually escaping commas on sql statements	select count(*) from tablename where yuzeyko = '29,59'; 	0.73961760424989
7245432	8194	list results in mysql from the same table	select a.`iduser` from `table` a  join `table` b on b.`iduser` = a.`iduser`  where a.`a`='gender' and a.`b`='man' and b.`a`='int' and b.`b`='woman' 	0.000115493595015002
7248329	34451	converting to mm/dd/yyyy format	select      convert(varchar,          convert(date, in_date, 103),      101) from dbo.sf_data 	0.182356937484429
7260377	36558	mysql many-to-many relationship select conditions	select  books.id,  books.title,  tags.id,  tags.name,  group_concat(distinct concat('["', tags.id, '","', tags.name, '"]') separator ',') as tags from flbdb_tags filter_tag join flbdb_books_tags filter_book_tags    on filter_tag.id = filter_book_tags.tag_id join flbdb_books books   on filter_book_tags.book_id = books.id join flbdb_books_tags books_tags   on books.id = books_tags.book_id join flbdb_tags tags   on tags.id = books_tags.tag_id where filter_tag.name like '%poetr%' group by books.id; 	0.228866498319545
7262415	27907	how to get the highest paid employee row	select e.* from employee e inner join (select dept, max(salary) ms from employee group by dept) m   on e.dept = m.dept and e.salary = m.ms 	0
7272404	21308	how do i get the last three digits of a varying length column?	select right(convert(varchar(4000), [hypothetical column]), 3) from table; 	0
7276663	35566	php mysql recipe search based on what ingredients are provided	select     * from     recipes where     rid not in (         select rid from relationship where iid not in (1, 2, 4)     ) 	0.0958576357129133
7295876	35038	sql query from variable tables	select         ep.type_attendant as `type`,         ep.id_attendant   as id,         concat( u.firstname, ' ', u.lastname ) as fullname     from         events_attendants ep       join         events e    on ep.id_event = e.id        join         users u     on ep.id_attendant = u.id     where         ep.type_attendant = 'user' union all     select         ep.type_attendant,         ep.id_attendant,         g.name       from         events_attendants ep       join         events e    on ep.id_event = e.id        join         groups g    on ep.id_attendant = g.id     where         ep.type_attendant <> 'user' 	0.0863828079218976
7297683	6392	retrieving and displaying categories and their children count	select c.category, count(p.id) as productscount  from categories c left join products p on c.id = p.category_id group by c.category     order by c.category 	0
7306082	37521	mysql - using group by and desc	select * from (select * from table order by time desc) as t group by numbers; 	0.551029330918492
7327415	37454	how do i get a count of items with identical ids in a mysql table?	select answer_id, count(*) as total from user_answers group by answer_id 	0
7333083	2157	mysql: counting items in many joined tables	select t.*, t1_count, t2_count from events t left join (select count(distinct id) as t1_count from tags) as t1 left join (select count(distinct id) as t2_count from tags) as t2 ... 	0.000870992923605237
7336413	12016	query grants for a table in postgres	select grantee, privilege_type  from information_schema.role_table_grants  where table_name='mytable' 	0.396611796636661
7351671	36846	how to calculate average time between intervals in sql?	select  customerid ,         sum(timesincelasttransaction) / count(*) from    ( select    * ,                     datediff(minute,                              ( select top 1                                         t2.datatime                                from     mytable t2                                where    t2.datatime < t1.datatime                                         and t2.customerid = t1.customerid                                order by t2.datatime desc                              ),                              t1.datatime                              ) as timesincelasttransaction           from      mytable t1         ) as individualtimes 	0
7360210	13176	how to order the records in a table using counts from other table which is grouped by a column?	select cl.classid, cl.name, count(no.notificationname) as classcnts from class cl left join notification no on cl.classid = no.class_id group by cl.classid order by classcnts desc 	0
7361530	10265	returning min and max order dates per client	select clientfield, min(orderdate), max(orderdate) from clienttable c inner join ordertable o     on o.clientid = c.clientid group by clientfield 	0.00364911759766913
7365742	6508	pivot to obtain eav data	select hmmmx = stuff((select ';' + [value] from @eavhelp      where [key] in ('key1', 'key2')     for xml path(''), type).value('.', 'varchar(max)'), 1, 1, ''); 	0.164614312264017
7373117	6665	asending order for hiredate	select ename, job, hiredate   from emp where hiredate between '20-feb-81' and '01-may-81' order by hiredate  asc 	0.335219300856598
7380579	22940	mysql copying from one table to another removes accents	select city from cities where binary city = 'gösselsdorf' 	0.000712445550653117
7388737	29309	sql loader associating variable number physical records with a single physical record	select      a.text,     b.text,     a.id,     a.nxtid  from  (     select text,id, nvl(lead(seq,1) over (order by id),999999) as nxtid     from t1 ) a left join t2 b on b.seq > a.id and b.id < a.nxtid 	0.000328733227356796
7400481	19958	mysql conditional queries	select g.name     from          visits as v       join         groups as g           on g.id = v.carer_id     where v.carer_mode = 0 union all     select c.name     from          visits as v       join         carers as c           on c.id = v.carer_id     where v.carer_mode = 1 	0.785748684101601
7406712	7240	question related to date and join	select o.orderdate, ol.order_id, p.product_id, p.name from order as o  inner join orderline as ol    on ol.order_id = o.order_id inner join  product as p on o    on p.product_id = ol.product_id where o.orderdate between  '2009-09-01' and '2009-09-30' ; 	0.257248503409548
7410102	11335	how to group by to get rid of duplicates rows	select min(pk), a, b, c  from @dummy  group by a, b, c 	0.000929220880218137
7421370	29461	adding days to a date	select `date`,        `numofdays`,        (`date` + interval `numofdays` day) as `newdate`   from `t1`; 	0.00074139324761672
7424505	27066	select * vs specific columns & loading object properties	select * 	0.102044988928057
7425531	18419	i want to get all jobs that are in dept 30 including the location	select deptno,        e.job,        d.loc   from emp e         join dept d using (deptno)  where deptno = 30 	0
7431420	23276	mysql: where statement that depends of the count() of a column?	select distinct cat_sub.*, count(job.job_id) as num_properties_which_meet_criteria from cat_sub left join job_cat using (sc_id) left join job using (job_id) where job.village_id=2  group by sc_id having count(job.job_id) > 0 	0.00119878145775126
7439259	1638	150m records order by name	select ... from members 	0.0127518861301308
7444908	15012	how to select only rows with the same number of duplicated columns?	select id, xid, [name]  from mytable where xid in  (    select xid from mytable    group by xid    having count(xid) = yournumber ) x order by xid; 	0
7462616	4828	django - aggregate sum of difference between datetime column	select sum(timestampdiff(second, first_action, last_action )) as total_time  from usersession where user_id = 123 and last_action is not null 	0.00478421002185111
7489109	9377	conditionally return records based on combination of field values	select yt.partnumber, yt.year, yt.make, yt.model     from yourtable yt     where yt.year = 2011         and not exists(select null                            from yourtable yt2                            where yt.partnumber = yt2.partnumber                                and yt.make = yt2.make                                and yt.model = yt2.model                                and yt2.year = 2012) 	0
7493523	23413	matching 2 columns in a table	select `city`, `prov`, count(`city`) as `countrink` from markers group by `city`, `prov` having `countrink` >=2 	0.00028403179491048
7494141	24	finding affected rows	select row_count(); 	0.00416305507304214
7504590	11978	left join, how to specify 1 result from the right?	select distinct l.*, a.strname as teamname  ... 	0.327875764290891
7516116	12616	sql - count and percent	select     count(i.id) as count    ,l.id    ,(     100.0 * count(i.id)      /       (       select count(i2.id)        from location l2       join item i2 on i2.locid = l2.id       where l2.id = l1.id      )    ) as percent    from location l    join item i on i.locid = l.id  where l.id in (36,38,39,40)  group by l.id 	0.0483250778609066
7526073	19863	concating fields with null values	select title,address,zip,city,concat(     coalesce(telefon1,''), ',',     coalesce(telefon2,''), ',',     coalesce(telefon3,'')) as phone 	0.0602370007729168
7526712	16278	selection constraint is plsql	select   id,   alias_one,   alias_two,   name from   (   select     id,     alias_one,     alias_two,     name,     count (distinct name) over (partition by alias_one, alias_two) as cnt   from entries   ) where cnt > 1 	0.319473622539981
7528058	15052	listing mysql tables and fields together	select table_name, column_name, column_type  from information_schema.columns where table_schema = 'my_db' order by table_name, column_name 	0.0403910520114647
7542907	19976	solution for finding "duplicate" records involving sti and parent-child relationship	select straight_join       sameweeksimilar.nextbasket,       count(*) nextbasketcount,       mainbasket.origcount    from        ( select count(*) origcount            from buyable b1            where b1.parent_id = 7 ) mainbasket       join       ( select distinct               b2.parent_id as nextbasket            from               buyable b1                  join buyable b2                     on b1.parent_id != b2.parent_id                    and b1.shop_week_id = b2.shop_week_id                    and b1.location_id = b2.location_id            where               b1.parent_id = 7 ) sameweeksimilar        join buyable b1           on sameweeksimilar.nextbasket = b1.parent_id     group by        sameweeksimilar.nextbasket     having        mainbasket.origcount = nextbasketcount 	0.0360616921571764
7554896	27627	first row as column header in openrowset	select * from   opendatasource('microsoft.jet.oledb.4.0',  'data source=c:\;  extended properties="text;hdr=no;fmt=delimited"')...[file#txt] 	0.00732175898971999
7555938	26338	getting specific rows from recordset	select * from (     select         @row := @row +1 as rownum, noun     from (         select @row :=0) r, nouns     ) ranked where rownum %4 =1 	0.00019124403704456
7558792	14190	sql like value from another table and wildcharcters	select t.ndc_10, p.ndc_8 from test t inner join product p on (locate(p.ndc_8,t.ndc_10) <> 0) 	0.00133111019230721
7566723	12699	how can i extract sprocs/tables/functions from a specific schema?	select     object_name(obj.object_id),     sch.name,     co.definition  from     sys.objects obj     join sys.schemas sch on sch.schema_id = obj.schema_id    left join sys.sql_modules co on co.object_id = obj.object_id where     sch.name = 'dbo'  	0.00191849857608878
7568653	23821	oracle group data	select *    from (select m.col1,                 m.col2,                 m.col3,                 sum(m.col4) sum_c4           from mytable m         group by rollup(m.col1, (m.col2, m.col3))        ) order by case when col1 is null then 1                else 0           end asc,                                               sum(sum_c4) over (partition by col1) desc,             col1,                                                  case when col2 is null then 1                else 0           end asc,                                               sum_c4 desc                                   	0.264021659605806
7571680	7069	how can i return a list of records and true or false if a joined record exists using sql?	select a.tablea_id, a.description,        case when b.tablec_id is not null then 'true' else 'false' end as doesexist     from tablea a         left join tableb b             on a.tablea_id = b.tablea_id                 and b.tablec_id = 123  	0
7573526	4944	self join in a table	select * from customer where referredby is not null 	0.57182920110128
7575114	22430	adding columns in sql select	select *, a.grosssales - a.credits as netsales from ( ) a 	0.0347816839070059
7577902	9057	i would like to delete the row with 0 (zeroes)	select m.project, e.hours, e.resources from mytable m      inner join       emptable e      on (      m.employeeid = e.employeeid       and       e.employeeid = @employeeid      and      (e.resources <> '0' and e.hours>0)     )  order by e.employeeid 	0.212656362282815
7581894	37110	ms sql rollup percentage column	select coalesce(cast(company as varchar(30)), 'grand total:') as company,        sum(sales)                                             as 'totsales',        sum(costval)                                           as 'totcost',        sum(marginval)                                         as 'totmar',        100.0 * sum(marginval) / sum(sales)                    as 'marginpercent' from   dailysalessum group  by company with rollup; 	0.287010333520034
7584815	40475	php & mysql - get top level category with just one query	select coalesce(c4.parent, c3.parent, c2.parent, c1.parent)  from categories as c1  left join categories as c2 on( c1.parent = c2.id )  left join categories as c3 on( c2.parent = c3.id )  left join categories as c4 on( c3.parent = c4.id )  where c1.id = {someid} 	0.000569897055907619
7594641	31598	mysql shortest query without results	select 1 from dual where 0 	0.250831307483586
7613785	34447	postgresql: top n entries per item in same table	select * from (    select uid,           title,            amount,            maker,            widgets,           rank() over (partition by maker order by amount desc) as rank    from entry   ) t where rank <= 3 	0
7627124	24677	selecting with a limit, but also a limit on the amount of times a column can have a specific value	select distinct *   from   posts p1  where  user_id in (2,1000001) and not track_id = 34 and         (select count(*) from posts p2              where p2.user_id = p1.user_id and p2.id > p1.id and p2.track_id <> 34)          <= 1  group by          track_id   order by          id desc limit 5 	0
7634534	16944	complex query across multiple tables	select c.candy_name, c.candy_type, s.softness, s.outer_coating_type,        s.animal_likeness,        group_concat(gc.color),        group_concat(gi.ingredient) from candy_main c left join gummy_standard s on s.candy_id=c.candy_id left join gummy_colors gc on gc.candy_id = c.candy_id left join gummy_ingredients gi cl on cl.candy_id = c.candy_id where c.candy_inventor_id=5 and c.candy_type='gummy' group by gc.color , gi.ingredient 	0.447153773902686
7646715	2207	ms sql : the best way to delete rows from a ginormous table	select 'starting'  while @@rowcount <> 0 begin     delete top (50000) dbo.mytable     output deleted.* into archivetable      where somecol < <afilter>     wait for delay ... end 	0.000695707681539623
7649663	33638	how to write an sql query that examines the previous row?	select b.stringname as stringname, a.stringname as previous_stringname     into #tmp     from (select stringname, row_number() over (order by id ) as row from testing) a     right outer join (select stringname, row_number() over (order by id ) as row from testing) b     on a.row = b.row - 1; select *, count(*) as [count] from #tmp group by stringname, previous_stringname; 	0.0049297260241356
7666527	25938	sorting a one-to-many join	select a.name, count(p.id) from albums a left join pictures p on a.id = p.album_id group by a.name order by count(p.id) desc limit 10 	0.583790494529166
7669276	35324	combine two tables in sql server 2008	select a,b,c from x  union all   select d, e, '' as f from y 	0.0470947444431293
7672747	28360	issue related to counting record on group by clause	select studentid, count(ispass)as passedcount from examentry group by studentid,ispass having ispass= 1 	0.0835309325167962
7678558	13896	how do i access a synonym from another scheme	select table_name    from all_tables   where owner='abcefh'     and table_name = 'plan_table'; 	0.00502363204562906
7690980	6979	oracle - cannot lookup row in database by uuid	select .... where id=hextoraw('08364fc81419429d83c9bcedb24a9a57') .... 	0.2566300504122
7692403	39004	how do i join names using the same table in sql?	select      child.siteuserfirstname + ' ' + child.siteuserlastname as childname,     parent.siteuserfirstname + ' ' + parent.siteuserlastname as parentname  from      siteusers as child inner join      siteusers as parent on child.siteuserparentid = parent.siteuserid where      child.siteuseractive = 1 	0.00200232889369055
7693500	13609	selecting all ids from a mysql query but with a limitation?	select id, content_timestamp from content c where author = 'newbtophp' and (select count(*)      from content      where date(from_unixtime(content_timestamp)) = date(from_unixtime(c.content_timestamp))      and content_timestamp < c.content_timestamp     ) < 3 order by content_timestamp 	0
7697792	27608	mysql drop tables where engine is memory	select table_name  from information_schema.tables  where table_schema = 'db1' and engine = 'memory'; 	0.693941483176972
7699700	16809	joining two tables in a select	select distinct   t1.* from   table1 t1   inner join table2 t2a on t2a.t1_id = t1.id and t2a.value = 'a'   inner join table2 t2b on t2b.t1_id = t1.id and t2b.value = 'b' 	0.00572465027382876
7704321	26595	merging rows in sql for similar ids?	select ga1.new_id, max(gl1.steam_id), max(gl1.origin_id), max(gl1.impulse_id), max(if(gl1.id = ga1.new_id,gl1.game_title,null)) as game_title from gl1, ga1 where (gl1.id = ga1.new_id or gl1.id = ga1.old_id) group by ga1.new_id union select gl2.id, gl2.steam_id, gl2.origin_id, gl2.impulse_id, gl2.game_title from gl2, ga2 where (gl2.id not in (     select ga3.new_id from ga3     union     select ga4.old_id from ga4)) 	0.000240319251984215
7710749	32583	mysql query for random id	select * from your_table order by rand() limit 1 	0.028764402435414
7717830	22511	group by same column where multiple condition using same column input	select       telco,        sum  (   case when hotkey = 'ib' then 1 else 0 end) as ib,        sum  (   case when hotkey = 'sb' then 1 else 0 end) as sb from        yourtable   group by    telco 	0.000536930366927242
7718628	29584	mysql query : involving 2 tables	select * from table1 t1, table2 t2, where t1.id = t2.id2 	0.141079374356624
7740255	38548	sql select every row in table1 that has a row in table2	select * from `users` as us      right join `usermeta` um1          on um1.`user_id` = us.`id`      where          exists (select 1 from `membership_renewals` mr                  where mr.`user` = us.`id`                  and mr.year = '2011')          and um1.meta_key = 'member'         and um1.meta_value = 1         and us.`user_pass` not like '-%' 	0
7742566	28073	mysql select query - exluding certain rows	select id, name from tire_brands  where id not in (select tire_brand_id from accepted_brands where shop_id=xxx) order by name 	0.00244923963666118
7744527	32272	limit download of data from sql in android app	select max(timestamp) from table; 	0.104807975429298
7745106	24827	mysql. sort on temporary column based	select * from album a join ( select yourlogic(rating) as total_no_photos,  album_id from photo       where yourlogic         group by album_id         ) temp_photo on temp_photo.album_id = a.album_id order by total_no_photos 	0.000942755980973704
7767478	24935	mysql match records between 2 tables	select t1.old_id, t2.new_id `matching new_id''s`, t2.east - t1.east `east difference`, t2.north - t1.north `north difference` from tb1 t1   join tb2 t2   on      t2.east between t1.east - 10 and t1.east + 10 and     t2.north between t1.north - 10 and t1.north + 10 	0.000307430904770769
7774238	16309	show duplicate records for a sql query	select a.asset, t.ticketnum, t.symptom_mask, t.setsolution, t.`otherdesc`    from lamarinfo as a    join lfso as t    on (a.id = t.asset_id)    where a.asset in (select asset from lamarinfo where open_dt between curdate() - interval 7 day and sysdate() group by asset having count(*) > 1) 	0.00148549518280062
7779864	16399	mysql join/union results from more tables	select max(views) as views,     max(column2) as column2,     max(column3) as column3 from (     select year(from_unixtime(date)) as year,          month(from_unixtime(date)) as month,          sum(views) as views,         0 as column2,         0 as column3     from stats     group by year, month     union     select year(from_unixtime(date)) as year,          month(from_unixtime(date)) as month,          0 as views,         sum(column2) as column2,         0 as column3     from stats     group by year, month     union     select year(from_unixtime(date)) as year,          month(from_unixtime(date)) as month,          0 as views,         0 as column2,         sum(column3) as column3     from stats     group by year, month ) group by year, month; 	0.0274028596236911
7789857	14917	how to bring closing balance to the opening balance	select mt.pipno,      mt.yyyymm,     mt.demand + isnull((select sum(balance) from mytable mt2 where mt.pipno=mt2.pipno and mt2.yyyymm < mt.yyyymm), 0) as demand,      mt.principle,     mt.interest,     mt.balance from mytable mt 	0.315684720555496
7791090	33613	sql query: how to get all employees with their information and all courses names with showing the courses that the employee has taken them	select   * from   employee left join employee_courses on (   dbo.employee_courses.employeeid = dbo.employee.badgeno ) inner join courses on (   dbo.courses.courseid = dbo.employee_courses.courseid ) 	0
7794679	38156	inserting values (generate_series) - how can i reuse/cycle the numbers, e.g, 1,2,3,1,2,3	select i as id, (i - 1) % 3 +1 as age, i as house_number into egg from generate_series(1,6) as i; 	0.00774640413883254
7797148	26520	how to optimizing a sql query for group counts with a priority column	select     highestgroupid,     count(*) as members from (     select         m.userid,         max(m.groupid) as highestgroupid     from membership m     group by m.userid ) sub group by highestgroupid 	0.168349741055092
7803062	14263	mysql output one instead of many	select distinct city from country_list where country='us' 	0.0137987431374275
7821739	13623	selecting top result from sql	select    t1.name,   t1.personid,   t2.timestamp,   t2.eventid,   t2.event from table1 t1 inner join table2 t2 on t2.personid = t1.personid inner join (select               personid,               max(timestamp) as lasteventdatetime             from table2              group by personid) le    on le.personid = t2.personid      and le.lasteventdatetime = t2.timestamp 	0.00175411567586299
7824597	26704	finding all duplicate rows in a table	select t1.*  from <table> t1, <table> t2  where t1.first=t2.first and    t1.last=t2.last and    t1.value<>t2.value ; 	0
7827341	35853	select where user roles 1 and 2 sql query	select users.id from users inner join roles_users on users.id = roles_users.user_id  where roles_users.role_id in (1, 2) group by users.id having count(*) = 2 	0.0168588714831777
7844726	6647	database select	select   film.filmname from   film   join film_category   on film.film_id = film_category.film_id where   film_category.category_id = 3 	0.139862629825159
7845080	19812	combining columns	select t.ename, t.deptno, mx.sal as sal, mx.avg_sal as avg_sal from tbl t,    (select max(sal) as sal, avg(sal) as avg_sal, deptno    from tbl    group by deptno) mx where t.deptno = mx.deptno and t.sal = mx.sal 	0.0254989648024062
7850503	40495	hashing in mysql	select sha1(concat('a=', p.itemid)) from items p where itemid = 412 	0.322618971319095
7860844	39377	adding (selecting) two more other columns to this resultset	select user_d      , date_of_application      , date_ended      , ( select te.grade          from tablex as te          where te.status = 'ended'            and te.user_id = t.user_id            and te.date_ended < t.date_of_application                order by te.date_ended desc          limit 1        ) as grade      , status from tablex as t where status = 'pending' 	0.00030859306924061
7872130	20856	how to select 1 last news for each category with join clause in mysql?	select c.category_name, a.title, a.body from all_news_table a inner join category_table c on (a.category_id = c.id) where a.id in (     select max(a1.id) from all_news_table a1     group by a1.category_id) 	0.000102660058842074
7872720	14110	convert date from long time postgres	select *, to_timestamp(time in milli sec / 1000) from mytable 	0.0306689330007036
7878237	37311	how display multiple rows in a table with one row in another table as single row	select      u.user_name,      sum(t.transactions) total from users u left join transactions t on t.user_id = u.user_id group by t.user_id 	0
7890400	25241	how can i get the certain value on the top of query result by sort?	select * from tbl order by case when status in (2, 3) then 0 else 1 end,      `status` 	0
7893504	35041	howto select from 3 columns and group as one without duplicate entries in mysql?	select genre1 as genre from yourtable union select genre2 as genre from yourtable union select genre3 as genre from yourtable 	0
7893627	19855	table with multiple columns containing employee keys. how to link to employee master to get names?	select a.col1      , a.boempid      , bo.empname      , a.adminempid      , ad.empname      , <....> from mytable a inner join employees bo         on a.boempid = bo.empid inner join employees ad         on a.adminempid = ad.empid 	0
7894553	7388	best way to retrieve data from few mysql tables with php	select product_id,model,name,barcode  from product  join product_descp  on product.product_id = product_descp.product_id 	0.00053437026065578
7901684	36876	separate commas from the table column	select doc_id,regexp_substr(terms_table.terms_array,'[^,]+',1,level) term  from terms_table   connect by level <= length(regexp_replace(terms_table.terms_array,'[^,]+')) + 1 	9.32682807271865e-05
7914579	558	sql query - find row which exceeds cumulative proportion	select top 1   t1.itemno from   mytable t1 where   ((select sum(t2.proportion) from mytable t2 where t2.itemno <= t1.itemno) >= 0.35) order by   t1.itemno 	0.00487497132491516
7919837	39225	how to query a table with multiple foreign keys and return actual values	select   ud.user_id, d.degree_type, ac.acad_cat_name, i.inst_name from  user_degrees ud  inner join degrees d on d.id = ud.degree_id  inner join acad_category ac on ac.id = ud.acad_id  inner join institutions i on i.id = ud.inst_id where  ud.user_id = 18 	0
7928134	5651	mysql multiple row literal select	select 1,2,3 union all select 4,5,6; 	0.0474010241724233
7931189	23305	how to query this column so that only entries from within the last week are taken	select * from yourtable as t1 where t1.last_updated > date_sub(now(), interval 7 day); 	0
7940720	29773	select most repeated values and sort them in mysql	select date, no, sum(c) c from ( select max(date) date, no1 as no, count(no1) c from table group by no union select max(date) date, no2 as no, count(no1) c from table group by no union select max(date) date, no3 as no, count(no1) c from table group by no ) grouped_data group by no order by c desc 	0.000207398185564949
7951616	2081	query to select the amount of rows in the databse for today's date?	select * from `orders` where date(`order_date`) = curdate() 	0
7955736	5901	sql multiple inclusive joins	select `cases`.* from `cases`  inner join `case_users` on `cases`.`id` = `case_users`.`case_id`  where `case_users`.`user_id` = '<user_id>'  union select `cases`.* from `cases`  inner join `case_groups` on `cases`.`id` = `case_groups`.`case_id`  where `case_groups`.`group_id` in (select `group_users`.`group_id`                                    from `group_users`                                    where `group_users`.`user_id` = '<user_id>') 	0.514418506870584
7956334	18890	plsql - trunc function - booking due within 24 hours	select studiono  from bookings  where to_date(date || time, 'dd-mon-yyyyhh24:mi:ss') < sysdate +1 and to_date(date || time, 'dd-mon-yyyyhh24:mi:ss') > sysdate 	0.0981690671822629
7957498	35573	get column names from blank stored procedure data set	select column_name  from information_schema.columns  where table_schema = 'dbo' and table_name = 'table_name' 	0.000125838294265442
7968731	40333	can i determine the group by clause based on a parameter?	select    ...,    datepart(yy, mydbdatefield),    case when @groupby = 1 then datepart(m, mydbdatefield) else null end,    case when @groupby = 2 then datepart(d, mydbdatefield) else null end from group by    datepart(yy, mydbdatefield),    case when @groupby = 1 then datepart(m, mydbdatefield) else null end,    case when @groupby = 2 then datepart(d, mydbdatefield) else null  end 	0.0266137357357028
7973150	24469	how to append html to the sql query	select top(@top) '<li><span><a href=''' + cu.url + '''>' + c.title + '</a></span></li>' from... 	0.0523704681461509
7976689	12274	how do i join these four tables with sqlite	select g.*, ((strftime('%s',r.checkout) - strftime('%s',r.checkin)) * rt.price/24/60/60) as total from guest g, reservation r, room rm, roomtype rt where g.guestid = r.guestid and r.roomnumber = rm.roomnumber and rm.roomtypeid = rt.roomtypeid 	0.285156013142375
7980815	11323	sql query to fetch rows where a value is present in a comma separated field	select * from table where find_in_set(3, product_cat_id); 	0
7997579	27536	sql server 2008 using rank to dynamically number rows	select rank() over (order by wl.lastname, wl.firstname) as rank, wl.lastname, wl.firstname  from  @tblwaitlist wl          inner join @tblseminar s  on wl.seminarguid=s.seminarguid      where s.seminarid = @seminarid and s.seminartype = @seminartype          order by rank ; 	0.0195636828967852
8000242	13851	mysql select query with sum()	select source_id, (sum(clicked)+sum(viewed)) as total from your_table group by source_id 	0.343946690182826
8000684	10866	joining to the same table in sql - sql server 2008	select  yt1.id ,       yt1.type ,       coalesce(yt2.description, yt1.description) as description from    yourtable yt1 left join         yourtable yt2 on      yt1.type = 'company'         and yt2.type = 'system'         and yt2.id = yt1.idofsystem where   yt1.type in ('system', 'company')         and not exists          (         select  *         from    yourtable yt3         where   yt1.type = 'system'                 and yt3.type = 'company'                 and yt1.id = yt3.idofsystem         ) 	0.0175632970860387
8002456	4940	optimization of multiple aggregations in select	select st.name,         avg(case when g.score < 65 then g.score else null end) as f,        avg(case when g.score >= 65 and g.score < 70 then g.score else null end) as d,        avg(case when g.score >= 70 and g.score < 80 then g.score else null end) as c,        avg(case when g.score >= 80 and g.score < 90 then g.score else null end) as b,        avg(case when g.score >= 90 and g.score <= 100 then g.score else null end) as a from grade g   join student st on g.studentid = st.id group by st.name 	0.518480403940538
8012949	35655	sql retrieve fields without a relation in another table	select ..., count(orders.id) as cnt from customers left join orders on (customers.id = orders.customer_id) and (orders.approved_at is null) having cnt = 0 	0.00018329826006026
8018485	29139	how do i find the busiest month using sqlite	select strftime('%m', checkin) as month, count(guestid) as tot from reservation group by month order by tot desc 	0.00147727152479375
8023416	32862	grouping results in a specific order	select t1.* from your_table t1 where t1.title =      (select title from your_table      where id_user = t1.id_user      order by title      limit 1) 	0.0329979604045271
8026097	15264	sum of 2 tables query using subqueries	select     (select sum(`upload_bandwidth`) from `upload_facts` where `date`        between '2011-09-01' and '2011-09-30')     +     (select sum(`download_bandwidth`) from `download_facts` where `date`        between '2011-09-01' and '2011-09-30') as `total` 	0.0767804870190292
8036853	40643	fetch result based on result of another query	select * from tablea where cloinab in (select colinab from tableb where colb = 5); 	0
8042006	30530	(sql-t-sql) select command to have only certain values?	select distinct appid from app_extra  where appid not in    (select distinct appid from app_extra     where appextraid in (9, 10)) 	0.000106051617573835
8046612	25186	aggregating on dependent columns	select     idy, count(distinct idx) as idxcount from     tablename group by     idy 	0.0243639040104451
8066930	5812	how can i query info from a special table structure in mysql?	select * from ( select     if(col1 is null,@c1,@c1:=col1) as col1,      if(col2 is null,@c2,@c2:=col2) as col2,      if(col3 is null,@c3,@c3:=col3) as col3,      col4, col5, col6 from     [table name],     ( select @c1:=0, @c2:=0, @c3:=0 ) x  ) y where col4 is not null; 	0.00960626477478682
8075323	14204	mysql with comma separated values	select table1.id, group_concat(table2.values) as values from table1 join table2 on find_in_set(table2.id, table1.nos) group by table1.id; 	0.00134641087392042
8091449	15544	sql select distinct with unique ids	select min(id), label from table  group by label order by min(id) 	0.00124933659383942
8091590	2727	sql to get an ordinal index in selection for specific id	select row_number() over (order by t2.[iid] asc) -1 as rowindex     ,[id]  from [dbo.test_db_002] t1 left join [dbo.test_db_003] t2      on t1.[id]=t2.[itmid]  order by t2.[iid] asc; 	0.0257971319251919
8093264	34607	sql query with inner join made to return specific values if matching a number	select items.id  , items.code  , items.description  , items.expirydate  , items.batchnumber  , items.serialnumber  , items.orderref  , items.datepurchased  , items.price  , items.consigcalloff  , items.commodity_qty  , itemtypes.code  , itemtypes.description  , locations.code  , locations.description  , keepers.code  , keepers.fname  , keepers.lname from items         left outer join join itemtypes on items.type = itemtypes.id         inner join keepers on items.keeper = keepers.id         inner join locations on items.location = locations.id` 	0.00343616326781441
8102858	28580	how do i find out if all fk references in the child table are present in the parent table	select * from user_emails where user_id not in (select id from user) 	0
8105869	23959	calculating all values in column	select product_id, sum(quantity) as totalquantity, sum(cost) as totalcost from order_product where order_ordernumber = 1100 group by product_id 	0.000762798942610258
8110857	20586	want to know how many photos are uploaded by a user. statistics table. sql	select firstname, count(*)  from members  join member_photos using(member_id)  group by firstname 	0.00119077754744944
8121494	31300	mysql: convert string to float/decimal in german language	select avg(convert(     replace(replace(value, '.', ''), ',', '.'),      decimal(10,2)))  from `table` where `group`=1 	0.210150205914803
8142211	23031	finding count and existence of id	select count(a1.id) as exists,         if(status = 'confirmed', 1, 0) as confirmed  from   foo f1         left join foo f2           on f1.id = f2.id  where  f1.id = 28 	0.000306312817598745
8146064	24471	mysqli operating with multiple tables	select u.id, u.fname, u.lname, u.mname, u.level,     u.pass, u.salt, u.approved, u.ban, u2.logged_in from `users` as u      left join `ulog` as u2 on u.id = u2.user_id where u.email=? 	0.250524319338713
8148115	11882	find a particular column's value that repeats the most in a table	select `artist id`, count(`cd id`) as `cd_count` from `table` group by `artist id` order by `cd_count` desc limit 1 	0
8149175	21637	adding order by with offset and limit in mysql query	select * from lead order by id desc limit 5 offset 0 	0.686217522022293
8149692	29552	using min() in multiple tables	select hotel_id, hotel_name, min(price) from region join region_contents     on regionname = <reqdname> and region.regionid = region_contents.regionid join prices     on region_contents.hotel_id = prices_hotel_id where end_date > now() group by hotel_id order by min(price) 	0.0816847304683261
8151494	40532	friend system in php/mysql?	select distinct a.username, a.profile_img from users a where a.id in (select user_a from friends where user_a = $userid or user_b = $userid) and a.id <> $userid union select b.username, b.profile_img from users b where b.id in (select user_b from friends where user_a = $userid or user_b = $userid) and b.id <> $userid 	0.354529237552667
8165534	28625	select rows not in another table, sql server query	select subjectid, departmentid, subjectname, subjectdescription, subjectshortcode from bs_subject  where not exists  (select subjecttoclassid from bs_subjecttoclass where  bs_subject.subjectid = bs_subjecttoclass.subjectid and bs_subjecttoclass.classid =2) 	0.0106339666587408
8166060	37508	sorting redundancies while fetching mysql entries using ordered sphinx search output	select id, cola, colb, ... from table where table.id in (id1,id2,id3,...) order by field (table.id,id1,id2,id3,....) 	0.0469967129172965
8185812	20316	select minimum from two tables using left join	select f.foo_id, f.a_string, min(d.dt) as 'my_date' from foo f left join (   select foo_id, min(a_date) as dt from a_dates group by foo_id   union select foo_id, min(b_date) as dt from b_dates group by foo_id ) d   on f.foo_id = d.foo_id group by   f.foo_id, f.a_string 	0.00688999891801075
8187369	31373	ssrs ..how to create drop down menu for different databases in same server	select name from master..sysdatabases 	0.00589320927775375
8200189	529	select random row from sql using php	select * from catalogue order by rand() limit 5 	0.00312762083233511
8212674	2214	return most recent visits to a users profile. group-by-n confusion	select v.viewer_id, max(created_at) as maxcreated     from user_profile     where viewer_id != 2         and v.user_id = 2     order by maxcreated     group by v.viewer_id; 	0.000247643342196023
8213354	11688	how to perform a complex range query in mysql	select t2.* from tablea as t1 inner join tablea as t2 on t2.fieldb >= (t1.fieldb - 100) and t2.fieldb <= (t1.fieldb + 100) 	0.528102102338609
8217756	24886	mysql subtract from isolated subquery	select      a.product_id   , a.cumulative as total_inventory   , a.cumulative - coalesce(b.quantity,0) as inventory_on_hand from table1 a join      ( select max(id) as max_id       from table1       group by product_id     ) m on (m.max_id = a.id) left join     ( select product_id, sum(quantity)        from table1        where in_transit = 1       group by product_id     ) b on (a.product_id = b.product_id) 	0.0519983968756898
8223352	6215	getting distinct ids in mysql	select id,comment from comments where id in (     select max(id)     from comments     where user_id=28 and deleted=0     group by review_id ) order by created desc 	0.00344111154198669
8272071	16423	mysql join count from one table with ids from another	select words.wordid, count(word_location.wordid) as appears  from words  left join word_location on word.id = word_location.wordid and article_id = ?  group by wordid 	0
8278893	18577	mysql query matching multiple fields	select       ul2.userid,       count(*) as likematches    from       userlikes ul1          join userlikes ul2             on ul1.likeid = ul2.likeid            and ul1.userid != singleuserbasisparameter    where       ul1.userid = singleuserbasisparameter    group by       ul2.userid    order by       2 desc 	0.0300133086484939
8281560	11376	carriage return symbol is removed from xml using openxml	select @node1 = replace(node.value('.', 'nvarchar(30)'), nchar(10), nchar(13)+nchar(10)) from @xml.nodes('/root/node1') as doc(node) 	0.287020651547578
8286274	41062	sql server displaying historical data	select * from product where @monthenddate  between fromdate and isnull(todate,get date()) 	0.113035406838241
8289436	25750	querying for rows without matching id in associated table	select * from problems where id not in (select problem_id from completed_problems where user_id = user_id)) 	0
8297484	40705	insert into ... select without detailing all columns	select * except somefield from 	0.000349510118451361
8297921	41286	how can i add second join which calculates an avg to this query?	select songs.title, avg(ratings.rating), count(something.songs_id) from songs left join something on (songs.songs_id=something.songsid) left join ratings on (songs.songs_id=ratings.songsid) group by songs.title 	0.199532928080609
8299781	23415	rolling back a transaction in t-sql after code has been executed	select * from dbo.maka where some_identifier = some_value 	0.17670319880582
8324117	19708	sql server: group by datetime without ticks	select convert(varchar(19), t.date, 120), count(*) as count from table t group by convert(varchar(19), t.date, 120)  having count(*) = 1 order by convert(varchar(19), t.date, 120) 	0.323788629237067
8344087	34434	find the most early hired employees in every department	select      a.department_name,     a.earliesthiredate,     b.first_name + ' ' + b.last_name as employeename from     (       select min(e.hire_date) as  earliesthiredate, d.department_name, d.department_id       from employees e join departments d         on e.department_id=d.department_id       group by d.department_name     ) as a     inner join employees as b         on a.earliesthiredate = b.hire_date             and a.department_id = b.department_id 	0
8346209	25271	recursive relations - list people with a supervisor and those without a supervisor	select o.official_name official, p.official_name supervisor from official o left join officialsupervisor s on o.official_id = s.official_id left join official p on p.official_id = s.supervisor_official_id 	0.00298987021604509
8348399	24918	returning rows from an implicit join where results either exist in both tables or only one table	select  pending.cl,         pending.id,         pending.buildid,         pending.build_type,         pending.active,         pending.submittracker,         pending.os,         pending.arch,         pending.osversion,         pending.branch,         pending.comment,         osversmap.osname,         buildlist.buildname,         results.logurl from pending     join osversmap         on ( pending.os = osversmap.os             and pending.osversion = osversmap.osversion )     join buildlist         on ( pending.buildid = buildlist.id )     left outer join results         on ( pending.active = results.hostname             and pending.submittracker = results.submittracker             and pending.cl = results.cl              and results.current_status != 'passed'             and results.current_status not like '%failed'             ) where pending.owner = '$owner'     and pending.completed = 'f' order by pending.submittracker,     pending.branch,     pending.os,     pending.arch 	0.000833033959373051
8359973	30940	with mysql, how to count members who are in an option and not in an other one?	select city_member,  count(id_member) as members,  sum(option1) as option1,  sum(case when option1 = '1' and option2 = '0' then 1 else 0 end) as non_option2 from my_table group by city_member 	0.000287231224351351
8367970	33544	database tables for reservation site	select * from rooms r where id not in (         select room_id         from bookings_rooms br             join bookings b on (br.booking_id=b.id)         where (checkin < :datea and checkout > :datea)             or (checkin > :datea and checkin < :dateb)     ) 	0.434412844838962
8369085	21194	get today's date in (yyyy-mm-dd) format in mysql	select curdate(); 	0.00117164323570787
8387595	21421	how to join two tables where one column in one table refers to 3 columns in other table?	select   user_activity.*,   initiator.name   as initiatorname,   source.name      as sourcename,   target.name      as targetname from   user_activity inner join   user             as initiator     on initiator.id = user_activity.initiator_id inner join   user             as source     on source.id    = user_activity.source_id inner join   user             as target     on target.id    = user_activity.target_id 	0
8391210	13204	how do i count users per group with mysql?	select group.id,count(users.username) from groups inner join users on users.group_id=groups.id group by groups.id 	0.00363342282102348
8413813	37641	how to select something from one table while checking status from another table?	select text from comments_table c  join users_table u on u.u_id = c.u_id and u.premium = 1 where c.u_id = ? 	0
8416347	1984	selecting similar, unique data rows from multiple mysql tables	select distinct name, email from   (select name, email from users    union    select name, email from clients    union    select name, email from administrators) p 	0
8433167	8654	mysql conditional field in join query	select  *, j.job_id as jid,  c.name as city_name  from jobs j  join areas a on a.area_id = j.job_area join positions p on p.position_id = j.job_position  join fields f on f.id = j.job_field join cities c on j.job_city = c.id  join jobtypes jt on j.job_type = jt.job_id join companies comp on j.job_company = comp.company_id  left join jobapplications ja on ja.applicantid = '$applicantid' and ja.jobid = j.jobid where   j.job_field = '$field'  and j.job_position = '$position'  and j.job_area = '$area'  order by j.creationdate desc" 	0.763158271401911
8438114	22194	sql: case when (with in param value)	select  (some columns) from   dbo.addressbook  order by   case     when city = @inparamcity then 0     else 1   end 	0.794910977803506
8438582	20646	mysql creating a top 10	select *, (price_shipping / abo_time + price / abo_time + abo_price) as month_avg  from db where model like '%iphone 4%' and model like '%16gb%' order by month_avg asc limit 10 	0.0179272108443694
8446721	40378	sql counting rows per day - firebird database	select cast(a.datetime as date) as day,count(*) from eventsgeneral a group by 1 	0
8451569	34739	dynamically setting year, while showing sum by month	select  case     when datepart(month, postingdate) = 1 then 'jan',     when datepart(month, postingdate) = 2 then 'feb',     when datepart(month, postingdate) = 3 then 'march',     when datepart(month, postingdate) = 4 then 'april',     when datepart(month, postingdate) = 5 then 'may',     when datepart(month, postingdate) = 6 then 'jun',     when datepart(month, postingdate) = 7 then 'jul',     when datepart(month, postingdate) = 8 then 'aug',     when datepart(month, postingdate) = 9 then 'sep',     when datepart(month, postingdate) = 10 then 'oct',     when datepart(month, postingdate) = 11 then 'nov',  else 'dec' as [month],  sum(amount) as total,  datepart(year, postingdate) as [year] from   table1 where   datepart(year, postingdate) <= datepart(year, getdate()) group by   datepart(year, postingdate) as [year],   datepart(month, postingdate) as [month] 	0.00285923384044797
8476879	34721	sql query limiting number of groups	select *  from `13_trans_coffee` where  `site code` =103713 and `date`  in ( select `date` from `13_trans_coffee` where `site code` =103713 group by `date` order by `date` desc limit 0 , 7 ) z; 	0.0110006025109664
8483309	36481	mysql count not returning 0 for specific id	select   c.c_id,   c_name,   (     select count(h.h_id)     from h     where h.h_id = c.c_id     and h.info_id = 25   ) as count  from c where c.c_id = {$sqlrow['c_id']} 	0.0201881818849482
8483413	19506	sql php recordset position	select count(id)+1 as rank from players where score>[yourplayerscore] 	0.0957064894899551
8495475	19423	time based data	select productid, date, sum(qty) as total from orders group by productid, date order by productid 	0.00214607013978048
8502214	34665	join two different columns from two different tables	select id1, name, id2, single, null from table1 union all select id1, name, id2, null, monthly from table2 	0
8509996	1739	is there a way to get the row number in mysql like the rownum in oracle	select @rownum:=@rownum + 1 as row_number,         t.* from (     < your original query goes here > ) t, (select @rownum := 0) r 	0.00125483554808588
8517816	17300	t-sql split word into characters	select substring(a.b, v.number+1, 1)  from (select 'qwerty anotherword' b) a join master..spt_values v on v.number < len(a.b) where v.type = 'p' 	0.010561708024003
8519811	33753	how to join two tables in sql query without repetition	select      id, name, age, gender, thumbnail  from (     select         rank() over (partition by m.id order by i.id asc) as rank,         m.id,         name,          age,          gender,          thumbnail     from         user_master m left join user_image i on (i.user_id = m.id) ) t where rank = 1 	0.176142546782277
8521752	6009	ibm.data.informix is not getting the correct data out of the database	select cast(timeid as nvarchar(9)), * from data 	0.0234763316059407
8522088	32181	get totals of invoice collection: total incl. - total excl. - tax by types	select code, sum(amount)      from sales_order_tax  group by code 	0
8528913	27003	get gridview row count with condition	select count(userrole) where userrole = 'admin' 	0.00414981147059212
8533962	1324	add +- 1 year in sql server	select productname from tblproduct where year between      (year(getdate()) -1) and (year(getdate()) + 1) 	0.01348019609591
8535942	12607	calculating minutes within a defined time window?	select [task end] - [task start] as taskduration from tasktable where [task start] > @windowstart and [task end] < @windowend 	0.0216534814691395
8536699	5582	sql query. intersect two tables: show matching records; but, in addition, show records if they exist in either table	select post_date,         sum(r1sum) as daily_batch,         sum(r2sum) as daily_sfs,         format( (sum(r2sum)/sum(r2sum+r1sum)), 'percent') as throughput from  (select day as post_date, (         col1+col2+col3+col4) as r1sum,          0 as r2sum   from d_vdr   union all  select post_date,          0 as r1sum,          sum(total) as r2sum   from sent_sf   where tmc=444 ) as sq group by post_date 	0
8538608	24916	mysql query for finding the weight of the edges in a graph	select     sp1.sid as sid1,     sp2.sid as sid2,     count(*) as num from     sp as sp1     inner join sp as sp2 on sp1.pid=sp2.pid and sp1.sid<sp2.sid group by sp1.sid, sp2.sid ; 	0.00125703080151258
8558163	3327	my sql query to retreive only duplicate records	select *  from entity  where entityname in  (select entityname   from entity   group by entityname   having count(*) > 1) 	0.00159649786765838
8567081	35484	how to select where like '%@param%'	select * from table where col like '%' + @param + '%' 	0.66292793409515
8576340	40076	query to find duplicate and duplicate with value	select min(a.rowindx)rowindx, b.rowindx rowindx1  from dedupinitial a, dedupinitial b  where a.rowindx < b.rowindx   and a.poivalue = b.poivalue  group by b.rowindx order by 1; 	0.000354818526306417
8591010	20665	getting multiple variables to show up in sql server?	select count(case when field = '1' then 1 end) as countone,        count(case when field = '2' then 1 end) as counttwo from   yourtable where  field in ( '1', '2' ) 	0.0640844785393899
8591526	13923	t-sql sorting by a calculated column	select      id,      price,      ismonthlyprice,      case ismonthlyprice     when 1 then price * 12 / 52     else price     end from [table]     order by          4 	0.0790315259471935
8595168	3224	calculating total overtime mysql	select sum(overtime)   from   (     select employee_id,            if(hour(sec_to_time(sum(timediff(time_out,time_in))))>40,               hour(sec_to_time(sum(timediff(time_out,time_in))))-40,               0) as overtime        from events       group by employee_id   )total 	0.00706838098805349
8602298	16012	oracle - maximum year query error	select * from (     select add_months(sysdate,-2)dt from dual     union all     select add_months(sysdate,-1) from dual     union all     select add_months(sysdate,2)from dual     union all     select add_months(sysdate,3) from dual     order by trunc(dt,'year') desc, trunc(dt,'month') asc ) where rownum = 1 	0.121645075522602
8607402	25636	search conditions across multiple tables	select ir1.recipe_id from ingredientsrecipes ir1 inner join ingredientsrecipes ir2 on ir1.recipe_id = ir2.recipe_id ... ingredientsrecipes irn on ir1.recipe_id = irn.recipe_id where  ir1.ingredient_id = 5 and ir2.ingredient_id = 121 and ... irn.ingredient_id = 80; 	0.0535202914265347
8615785	27391	how to load data to gridview programmatically?	select  case when mode ='c' then amount else '-' end as credit, case when mode ='d' then amount else '-' end as debit from tbl 	0.357460682410603
8618414	1682	mysql join sum query	select tblemployee.first_name, tblemployee.last_name, sum(tblevents.points) as points from tblevents inner join (tblemployee inner join tblpoints on tblemployee.employee_id = tblpoints.employee_id)  on tblevents.events_id = tblpoints.events_id group by tblemployee.employee_id; 	0.578751538763807
8628195	21414	how to apply or to join...on statement	select p.id   from place_user_relation r join place p on p.id = r.place_id  where p.author_id = 1     or r.user_id = 1 	0.721714498502946
8635595	38898	how to get only the date from datetime information in sqlserver?	select     count(distinct dbo.userquiz.quizid) as [total number of taken quizzes], dbo.divisions.divisionname, convert(varchar,dbo.userquiz.datetimecomplete,110 )                        as month from         dbo.userquiz inner join                       dbo.quiz on dbo.userquiz.quizid = dbo.quiz.quizid inner join                       dbo.employee on dbo.userquiz.username = dbo.employee.username inner join                       dbo.divisions on dbo.employee.divisioncode = dbo.divisions.sapcode group by dbo.divisions.divisionname,convert(varchar,dbo.userquiz.datetimecomplete,110) 	0
8637035	20850	query to find duplicate record in oracle	select min(a.rowindex)rowindx, b.rowindex rowindx1  from dedupinitial1 a, dedupinitial1 b  where a.rowindex <= b.rowindex   and a.name = b.name group by b.rowindex order by 1; 	0.00212233377764886
8654627	8750	datetime query on only year in sql server	select id,name,bookyear from tab1 where year(bookyear) = 2009 	0.00512545027906054
8663014	2454	mysql query group by custom month date?	select       count(o.orderid) as number_of_orders,       concat(          monthname( date_sub( from_unixtime(o.`date`), interval 10 day )),          ' - ',          year( date_sub( from_unixtime(o.date), interval 10 day) )             ) as ordered_month,       sum(o.total) as totalamount,       month( date_sub( from_unixtime(o.`date`), interval 10 day )) as month_of_year,       year( date_sub( from_unixtime(o.date), interval 10 day )) as sale_year    from        orders o    group by        month_of_year,        sale_year    order by        sale_year desc,       month_of_year desc 	0.0274994761176422
8676646	27269	how to select many different data"s" from two table?	select a.ip from tablea a where tablea.ip not in (select b.ip from tableb) 	0
8717935	16067	how to store multiple values from select in sql server? 	select @value1 = one, @value2 = two from dummytable; 	0.0204435792630287
8722022	29448	need to calculate by rounded time or date figure in sql server	select     dateadd(minute, datediff(minute, 0, foo), 0),                   dateadd(minute, datediff(minute, 0, foo) / 5 * 5, 0),           dateadd(minute, datediff(minute, 0, foo) / 10 * 10, 0),         dateadd(minute, datediff(minute, 0, foo) / 15 * 15, 0),         dateadd(minute, datediff(minute, 0, foo) / 30 * 30, 0),         dateadd(hour, datediff(hour, 0, foo), 0),                       dateadd(hour, datediff(hour, 0, foo) / 2 * 2, 0),               dateadd(day, datediff(day, 0, foo), 0),                         dateadd(day, datediff(day, 0, foo) / 5 * 5, 0),                 dateadd(day, datediff(day, 0, foo) / 10 * 10, 0),               dateadd(month, datediff(month, 0, foo), 0),                     dateadd(month, datediff(month, 0, foo) / 2 * 2, 0)          from     @dates; 	0.545713078293958
8726662	18521	mysql express a subset of results from a query (i.e. two queries) as a percentage	select tot.day,tot.total,ifnull(s.total,0) as searchtermtotal, round(100*ifnull(s.total,0)/tot.total,2) as percentage from (   select date_format(logtime, '%d.%m.%y') as `day`,    count(date_format(logtime, '%d.%m.%y')) as `total`   from log    group by `day` ) tot left join (   select date_format(logtime, '%d.%m.%y') as `day`,    count(date_format(logtime, '%d.%m.%y')) as `total`   from log    where message like '%searchterm%'   group by `day` ) s on s.day = tot.day; 	0.000640713143658135
8736330	36017	sql result: non-empty categories	select   categories.name,   ... from   categories   inner join partcategories on partcategories.categoryid=categories.categoryid   inner join parts on partcategories.partid=parts.partid   inner join manufacturers on parts.manufacturerid=manufacturers.manufacturerid where   manufacturers.manufacturerid=<your chosen manufacturerid> 	0.13105752853811
8743578	19017	query with if statement	select c.status, c.thumb,         j.id, j.name,         j.username, s.session_id,         a.time, a.isactive,         a.country, a.countrycode, a.city,        if(a.time > date_sub(now(), interval 1 minute), 1, 0) as isonline from j16_users as j       join j16_community_users as c on c.userid = j.id       left join j16_session as s on s.userid = j.id       left join j16_session as s on s.userid = j.id       left join j16_x5_fastchat_users as a on a.userid = j.id  where j.id in (62,66,2692) 	0.778943139470073
8761339	11210	sybase add incrementing counter to a select statement	select counter = identity(10), data1, data2 into #t1 from tablename select * from #t1 drop table #t1 	0.129154159294155
8763747	39094	select from two tables from different databases	select t1.id, t1.name, t2.id, t2.telephone from db1.table1 t1 inner join db2.table2 t2 on t1.id = t2.id; 	0
8765503	5220	how can i check identity in 1 column in sql query?	select      case          when min(column1) <> max(column1) then 'false'          else 'true'      end  from mytable 	0.0269011078035149
8770951	3376	columns equal to something in mysql	select (if exists (select local from database where local='something'),"equal","not equal"); 	0.0323618624042282
8778372	28657	mysql select 3days records from today	select * from `user`  where name !=''  and `date_created` between curdate() and curdate() + interval 3 day order by `date` 	0.000377458754477108
8779031	1683	simple sql server count query (counting changes to values in a column)	select p1.mm,p1.yyyy,count(*) from projs p1 join (select projid,min(yyyy*100+mm) as closedon from projs        where stat='c' group by projid) xx        on xx.projid=p1.projid and p1.yyyy*100+p1.mm=xx.closedon where p1.stat='c'  group by p1.mm,p1.yyyy 	0.0772037510100903
8779585	21570	select random rows from mysql table	select * from table order by rand() limit 10; 	0.000362340235820891
8779918	19899	postgres multiple joins	select animal.id, breed1.breedname as breedname1, breed2.breadname as breadname2  from animal     left join breed as breed1 on animal.breedid=breed1.id     left join breed as breed2 on animal.breedid=breed2.id  where animal.id='7'; 	0.523561745254995
8797784	31567	calculating the difference of the sum of two different columns from two tables	select c.cashier_name as cashier,      coalesce( salesbycashier.totalsales, 0 ) as sales,     coalesce( refundsbycashier.totalrefunded, 0 ) as refunds,     coalesce( salesbycashier.totalsales, 0 ) -        coalesce( refundsbycashier.totalrefunded, 0  ) as total from   cashier c left join    ( select s.cashierid as cashierid, sum(amountreceived) as totalsales      from sales s      group by s.cashierid ) salesbycashier on c.cashierid = salesbycashier.cashierid left join    ( select r.cashierid as cashierid, sum(amountrefunded) as totalrefunded      from refunds r      group by r.cashierid ) refundsbycashier on c.cashierid = refundsbycashier.cashierid 	0
8801946	33730	uncategorized products query	select p.product_id, p.name from category_product cp join product p on cp.product_id = p.product_id group by cp.product_id having sum(case when category_id in (2,5) then 0 else 1 end) = 0 	0.132208529783906
8810779	3249	selecting a default value if an entry doesn't exist	select u.name,         coalesce(ql.quota1, (select quota1 from quota_level where quotalevel = 'bronze'))     from users u         left join user_info ui               inner join quota_level ql                 on ui.quotalevel = ql.quotalevel                           on u.id = ui.userid 	0.000539624994293682
8811449	27665	slow sql queries, order table by date?	select distinct n.testname  from            [dalsate].[dbo].[resultsuut] u  inner join      [dalsate].[dbo].[resultsnumeric] n      on n.modedescription = 'mode 8: low gain - green-blue'      and n.resultsuutid = u.resultsuutid where           u.devicename = 'bo-32-3hk60-00-r'                  and u.startdatetime > cast('2011-11-25 01:10:10.001' as datetime) order by        n.testname 	0.664550769752155
8814429	30549	create view with year days	select add_months(trunc(sysdate - (365), 'yyyy'),to_number(to_char(sysdate,'mm'))) + (level - 1) as the_day   from dual connect by level <=            to_number(to_char(last_day(add_months(trunc(sysdate, 'yyyy'), 11)),                              'ddd')) 	0.000967482274764345
8821824	14606	mysql select query with multiple where	select * from posts where post_id in ( "15" , "14" ) 	0.527936862283963
8828364	34043	using "like" inside a "case" statement with 2 different fields	select      case        when col2 = 'n'         or col1 like '%c.txt'           then '0'       when col2 = 'y'           then '1'     end as col3   , *  from tabl1 	0.756381345063985
8829354	14568	sql combine 2 queries with join	select   count(*) as count, g.id, g.name, g.color from     gangs g join turfs t on t.gang = g.id where    city = '$city' group by g.id, g.name, g.color 	0.188697634140062
8840142	37775	select only string with number sql server	select id     from yourtable     where isnumeric(name + '.0e0') = 0 	0.0069402638958743
8841868	1402	how to count the relations between names in the same table?	select n1.name as "name 1", n2.name as "name 2",     count(*) as "count" from "names" as n1 join "names" as n2     on n1.group = n2.group where n1.name <> n2.name group by n1.name, n2.name 	0
8862868	14730	mysql join two tables with different row on left side and same row on right side	select table1_ride.id, fc.name as from_city_name, tc.name as to_city_name from table1_ride inner join table2_city as fc on     table1_ride.from_which_city=fc.id inner join table2_city as tc on     table1_ride.to_which_city=tc.id 	0.000289551616860689
8864198	16021	php - compare connections/feed from two mysql tables	select feed.* from connections join feed   on connections.friend_id = feed.user_id where connections.user_id = <insert id of user> 	0.000618883036844255
8870687	31122	creating a sql statement to return user ids that purchase multiple items	select distinct(ipod.user_id ) from sales ipod     inner join sales shoes on shoes.user_id = ipod.user_id      inner join sales bike on bike.user_id = ipod.user_id  where ipod.item  = 'ipod'      and shoes.item = 'shoes'     and bike.item = 'bicycle' 	8.36688169959473e-05
8874136	32126	return first table data regardless if second table returns data, operator join normalization	select *  from sections as cs  left join pages as cp on (cp.id_section = cs.id and cp.url like binary 'not exists')  where cs.section_url like binary 'section_url' 	0.000309483660371784
8880862	18266	add days to a date php object and then verify if it is between 2 date objects	select   * from     users where    date between curdate() and date_add(curdate(), interval 15 day) 	0
8899327	13507	optimizing a sql query finding entries that do not exist in table	select distinct m.name from @mytable m left outer join job_log j on j.name = m.name and j.start_date > @startdate and j.start_date < @enddate where j.name is null 	0.00707059380591247
8900407	25142	query returns additional rows	select * from (select *    from messages   where from_user = ?   or to_user = ?   order by from_user, to_user, sent desc ) x group by from_user, to_user order by sent desc limit 1; 	0.160011292540933
8907198	13365	how to find values from one table to limit other table?	select * from questiontable where id not in     (select idofquestion as id from tablequestion where user = 'userhere') 	0
8910370	14701	merge two columns into one column and get unique	select childcard as cardid from tbl union select primarycard from tbl 	0
8911983	39450	how to select records if the absolute value of the difference between two values if greater than a certain number?	select * from yourtable where abs(lap_time_1 - lap_time_2) > 30 	0
8918036	14145	not selecting repeat data sql	select distinct make      from yourtable     order by make; 	0.0233645395374616
8930791	33937	populate dataset with table names from stored procedure	select *,'mytablename1' as [tablename] name from mytablename1    select *,'mytablename2' as [tablename] name from mytablename2 	0.00416933784156452
8935821	36453	sum() of calculated field	select a.one,a.two,a.three,a.four,sum(a.four) as 'sum' from (select c.one,c.two,c.three,c.four   from mytable c   where c.one = 11052 and c.three = 97734   group by c.one, c.two,c.three , c.four) a 	0.0078664460731151
8943896	12733	top, sum sql statement	select        rpt.codenumber     , rpt.axsubgroup     , rpt.itemstructure     , rpt.unitssold     , rpt.dollars     , grp.totalunitssold from        rpt   join       ( select top 20                axsubgroup             , sum(unitssold) as totalunitssold         from               rpt          group by               axsubgroup         order by               totalunitssold desc       ) as grp     on        grp.axsubgroup = rpt.axsubgroup order by       rpt.axsubgroup 	0.197864622565823
8958143	26577	database table structure for user albums and photos	select a.*, u.username from albums a inner join users u on u.userid = a.userid where a.userid='$userid'; 	0.00845985079821185
8960759	11172	mysql - get a row for each year, with total sum for each month	select   year(dt) as the_year,   sum(case when month(dt) = 1 then mc_gross else 0 end) as total_jan,   sum(case when month(dt) = 2 then mc_gross else 0 end) as total_feb,   ...   sum(case when month(dt) = 12 then mc_gross else 0 end) as total_dec from   transactions group by   the_year; 	0
8963929	31755	mysql find duplications	select uid, count(*) from table where fid=1 and `time` > 9 group by uid 	0.292586115788529
8983677	9355	mysql select query - add two rows and display them as one?	select   receive.receipt_date, supplier.name, item.name as expr2, receive_item.price,   receive_item.qty,    receive_item.qty - ifnull(sum(delivery_item.qty), 0)) as 'remained qty.' from   receive_item inner join   receive on receive_item.receipt_id = receive.receipt_id  inner join   supplier on receive.supplier_id = supplier.id  inner join   item on receive_item.item_id = item.id  inner join   po on receive.po_number = po.po_id  left outer join   delivery_item on receive_item.item_id = delivery_item.item_id    and receive_item.receipt_id = delivery_item.receive_id  group by receive.receipt_date, supplier.name, item.name as expr2,    receive_item.price, receive_item.qty; 	0
8988408	40067	get xml schema used by sql column	select c2.name from sys.columns as c1   inner join sys.xml_schema_collections as c2     on c1.xml_collection_id = c2.xml_collection_id where c1.object_id = object_id('tablename') and       c1.name = 'columnname' 	0.0532238791391156
8994718	32095	mysql longitude and latitude query for other rows within x mile radius	select *, ( 3959 * acos( cos( radians($centerlat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($centerlng) ) + sin( radians($centerlat) ) * sin( radians( lat ) ) ) ) as distance from markers having distance < 25 order by distance limit 0 , 20 	0.030570489493188
8995268	31771	limit, choice the union duplicate checking columns	select  cod, des  from parameters1 p1 union all select  cod, des  from parameters2 p2 where not exists (     select 1     from parameters1 p1sub     where p1sub.cod = p2.cod ) 	0.0133018897147129
8998801	21099	sql query between two tables	select     a.bossid as bossid, b.name as name, a.empid as empid, c.name as name from       boss a left join  emp b    on         a.bossid = b.id left join  emp c     on        a.empid = c.id 	0.0213944109395737
9009721	22073	double mysql query	select messages.* from messages  left join log on log.message_id = messages.id and log.ip = '$ip' where state = '-1' and log.ip is null 	0.743852066366721
9011611	40617	count from 2 tables based on one-one, many-one, and many-many relationship	select t3.id from (select distinct id from t1) t3 inner join t2 on t3.id = t2.id 	0
9013531	22733	subquery getting the parent addedby field	select s.level, s.sequence, s.postid, s.addedby,     s.title, s.parentid, s.path_string,    owner = coalesce(o.addedby, s.addedby) from cte as s left outer join cte as o on s.parentid = o.postid order by s.sequence; 	0.0163204997851668
9029154	32937	multiple tables (one is a subquery) join	select u.`name` as username,        count(*) as countaccts,        sum(a.`amount`) as sumaccts,        coalesce(itable.countacctsthisyear, 0) as countacctsthisyear from    `user` u inner join `accounts` a                     on u.`id` = a`.`id`                left join                    (select `id`, count(*) as countacctsthisyear                     from `accounts`                     where date_format(`date`,'%y') = date_format(curdate(),'%y')                     group by `id`) as itable                 on `user`.`id` = itable.`id` group by `user`.`name` 	0.13331798678952
9030889	15759	group by month in sqlite	select strftime('%m',`date`) as `month`,        avg(weight) as `amount ` from babydata where `date` between date('2011-2-2')                         and                       date('2011-2-2','+12 month') group by `month` 	0.0211954227062112
9046764	35631	select two counts in one query	select sum(case when user = 'x' then 1 end) usercount, sum(case when email = 'x' then 1 end) emailcount from users 	0.00484815993007284
9050353	15413	make sql query from four table	select u.username as user, i.image as user_image, count(*) as comments from users u               inner join user_follow f on u.id = f.follow_id inner join images p on p.user_id = u.id inner join commentaries c on c.image_id = p.id where u.user_id = 3 group by u.username, i.image; 	0.0476317127759761
9076524	3100	mysql query modify	select  cl_brands.name as brand,date_format(cl_doctor_call.date_entered,'%b%y')as monthyear, sum(find_in_set(concat('^',cl_brands.id,'^'),cl_doctor_call_cstm.brand_discussed_c))as no_times_brand_discussed from cl_doctor_call left join cl_doctor_call_cstm on cl_doctor_call.id=cl_doctor_call_cstm.id_c  left join cl_brands on concat('^',cl_brands.id,'^') like concat(cl_doctor_call_cstm.brand_discussed_c, '%' ) where brand_id in  (    select c1.brand_id    from cl_doctor_call left join cl_doctor_call_cstm on    cl_doctor_call.id=cl_doctor_call_cstm.id_c     left join cl_brands on    concat('^',cl_brands.id,'^') like concat(cl_doctor_call_cstm.brand_discussed_c, '%' )    where (cl_doctor_call.date_entered)    between curdate()-interval 3 month and curdate()    group by cl_brands.name,monthy`enter code here`ear )  order by date_entered limit 3 	0.585968412440756
9091631	27731	statement to get complete table ? in sql server?	select *   from tbl_file_extn_m fem     left outer join  tbl_file_extn_emplink_m feem on fem.extid = feem.extid and feem.empid = '004135' 	0.208620957241362
9101795	2743	combining 2 views into one in postgresql	select col1,col2 from table union all select col1,col2 from some_other_table union all select col1,col2 from yet_another_table; 	0.0018384766698412
9116663	22858	how to do a 'count' for several criteria at once	select   case     when total=1 then 'one'     when total=2 then 'two'     when total=3 then 'three'     when total=4 then 'four'     when total=5 then 'five'     when total=6 then 'six'     when total=7 then 'sevenplus'   end,   count(total) from   (select case when count(uniqid) <= 6 then count(uniqid) else 7 end as total from otcdata3 group by uniqid) as totals group by total order by total 	0.000302209426222146
9151706	12844	getting row number for query	select categoryid,        name,        (select count(*)         from mytable as t2         where t2.name <= t1.name) as row_num from mytable as t1 order by name, categoryid; 	0.0039592008047658
9161118	33347	assign a field a value from another table, based on another fields value	select case c.cardnametype             when 0 then f.name             when 1 then m.name             when 2 then c.name        end as [card owner] from     card c inner join     father f on f.account# = c.account# . . . 	0
9161242	21276	getting the good row in a mysql group by query	select id, date, movie_id, comment_value from comments c join (select movie_id, max(date) date from comments group by movie_id) x on x.movie_id=c.movie_id and x.date=c.date group by movie_id; 	0.0840602330313847
9185265	9474	display result of query without primary key	select (* except some_col) 	0.000651802937312912
9191786	16660	sql query - grouping data	select t.receiver as person, count(t.day) as lastreceivertotal from throws t inner join (select max(thrownum) as lastthrownum, day from throws group by day) a on a.lastthrownum = t.thrownum and a.day = t.day group by t.receiver 	0.262979175749623
9193100	25716	sql query to get all records from one table, except a specific record, by date, from another table	select       t1.*    from       table1 t1          left join table2 t2             on t1.t2.t1id           and t2.date = '2012-02-08'    where       t2.t1id is null 	0
9195644	21246	how to fetch only a value from mysql database?	select name from top_categories where top_categories.id = your_id   order by name asc  limit 0,1 	0
9212634	8736	in mysql how do i use my table reference twice for a single select?	select s.title, u1.value * s.drive_value as drive, u2.value * s.cache_value as cache from storage s inner join unit u1 on u1.id = s.drive_unit_id inner join unit u2 on u2.id = s.cache_unit_id 	0.0766713073075057
9216176	19092	regex mysql - match first two letters, x numbers	select * from t3_seriesinfo where vectorid regexp '^ts[[:digit:]]+' order by vectorid desc 	0
9219669	19577	query select data with any character not a-z|0-9|#|space	select * from table  where field_name not regexp '[a-z]|[0-9]|[:space:]'; 	0.542352422932335
9223515	28674	using order by for month with year	select column1 from yourtable order by convert(datetime, left(column1, 3)+' 01, '+right(column1, 4), 107) 	0.00326156323126816
9244343	38540	my sql list unmatched rows in joins	select p.id, p.propertyname, pt.typename from properties p inner join property_types pt on (p.typeid = pt.id) where not exists (    select 1    from properties_rent    where year = 2012    and propertyid = p.id ) 	0.165902999719635
9252825	34196	how can i group the results of a many-to-many via sql as opposed to using php to do so?	select      users.username, users.address,      group_concat(projects separator ', ') as projects from     users join projects_to_users          on users.user_id = projects_to_users.user_id     join projects         on projects_to_users.project_id = projects.project_id group by     users.user_id; 	0.185457078120677
9269105	15381	selecting multiple values from two table at once	select message.*, recipient.*, sender.* from msghistory as message inner join users as recipient on recipient.id=m.to_id inner join users as sender on sender.id=m.from_id 	0
9279518	40492	in mysql, how do you dynamically select the values of one table, as columns in another?	select fav.user_id, u.name         max(case when fav.fav_key = 'icecream' then fav.fav_val end) as 'fav_icecream',        max(case when fav.fav_key = 'candybar'  then fav.fav_val end) as 'fav_candybar',        max(case when fav.fav_key = 'color'    then fav.fav_val end) as 'fav_color' from favorite fav      inner join users u on fav.user_id = u.user_id group by fav.user_id 	0
9280555	1191	most efficient way to access/write data to sqlite on android	select value from preferences where key= ? limit 1 	0.0592628447275685
9280724	12994	sql multi layer headers	select lastmonthserver, lastmonthapplication, lastyearserver, lastyearapps  from ....  where ....  order by ... 	0.564861054958534
9290209	18400	get ids for a given date range	select id from bulbs where end_date >= '2012-02-10' and start_date <= '2012-02-20' 	0
9305689	10903	finding latest month, year including the other fields	select highestyear.* from (   select v1.* from visitors v1   left join visitors v2   on v1.number = v2.number and v1.year < v2.year   where v2.year is null ) highestyear left join visitors v3 on highestyear.number = v3.number and highestyear.year = v3.year and highestyear.month < v3.month where v3.month is null 	0
9308590	5457	two date columns and one date range , typical query?	select sum(daydifference * charge_per_day) +          (realdaydifference - sum(daydifference)) * 25 as totalperperiod from (   select charge_per_day, datediff(       least(end_date, '2012-02-22'),       greatest(start_date, '2012-02-15')) + 1 as daydifference,       datediff('2012-02-22', '2012-02-15') + 1 as realdaydifference   from t1   where     ((start_date between '2012-02-15' and '2012-02-22') or     (end_date between '2012-02-15' and '2012-02-22') or     (start_date < '2012-02-15' and end_date > '2012-02-22'))     and hotel_id=6 ) s1 	0
9308867	6337	mysql group_concat with sums also inside	select concat('{', group_concat(c1), '}') from (   select concat('"', type, '":', sum(amount)) c1 from t1 group by type   ) t 	0.369700608226997
9318959	181	complicated result distribution database query	select s.track_name,s.id from    (select id, track_name, music_type, row_number() over (partition by music_type) as r       from tracks ) s,     preferences p     where username='billy'     and p.music_type=s.music_type     and s.r<=p.percentage     order by s.id 	0.730142583069571
9323982	19296	how to get the list of table names from database in sorted order according to there creation date?	select table_name,create_time from information_schema.tables where table_schema = 'yourdatabasename' order by create_time asc; 	0
9328748	12138	how to write sql query for the scenario?	select id1, d1.name as i1_name, d2.name as i2_name, d3.name as i3_name from demo2, demo1 as d1, demo1 as d2, demo1 as d3 where demo2.i1 = d1.id, demo2.p1 = d2.id, demo2.p2 = d3.name 	0.718991918472589
9331569	3035	how to generate an order index value (as in the order of a list) in a select statement	select b.id, b.tablea_id,         row_number() over(partition by b.tablea_id order by b.id) - 1 order_index,        b.name  from tableb b left join tablea a on b.tablea_id = a.id 	0.00108087688753985
9332301	24299	alternative to mysql union	select a, b, c, d from t1 union select a, b, null, 0 from t2 union select '', b, c, 1 from t3 	0.792541338995504
9337886	34368	mysql group by with additional conditions	select *  from jobs  group by case when jobtype in ('1','2') then '1' else jobtype end, address1 	0.564660431953357
9345737	36054	how to create two column output from a single column	select first_name.value, last_name.value from your_table first_name join your_table last_name on first_name.uid = last_name.uid where first_name.fid = 5   and last_name.fid  = 6 	5.78630720003489e-05
9347225	4078	mysql left join with three tables	select count(*) as match_count from clan_members c, roster_members r, match_players m where c.member_id = r.clan_member_id and r.id = m.roster_member_id and c.id = 123 	0.691463271531026
9357832	26538	need the sql query	select a.nvrequipment as [equiment name],a.availability,b.breakdown,c.idle, (b.breakdown + c.idle) * 100 / nullif(a.availability, 0) as utilization from  (select nvrequipment,sum(fltquantity) as [availability] from tblequipment  where intstatus in(1,2,3) group by nvrequipment) a left join  (select nvrequipment,sum(fltquantity) as [breakdown] from tblequipment  where intstatus = 2 group by nvrequipment) b on a.nvrequipment=b.nvrequipment left join (select nvrequipment,sum(fltquantity) as [idle] from tblequipment  where intstatus = 3 group by nvrequipment) c on a.nvrequipment=c.nvrequipment 	0.616758111976127
9357936	16645	sql: sum(unit) table a minus sum(unit) table b	select   item_id,   sum(unit) as unit_balance from (   select item_id, unit from item_in   union all   select item_id, -unit from item_out ) as s (item_id, unit) group by item_id 	0.0235368242773039
9361636	22778	sql join with three tables	select     *,     (select count(*) from posts where posts.userid = users.id and opinion = 'agree') compliments,     (select count(*) from posts where posts.userid = users.id and opinion = 'disagree') complaints,     (select count(*) from reactions where reactions.userid = users.id and opinion = 'agree') positive_reactions,     (select count(*) from reactions where reactions.userid = users.id and opinion = 'disagree') negative_reactions from users 	0.348350209094767
9382226	16827	creating a view in mysql	select userid,        sum(case when column_a<>0 then time else 0 end) as columnasum,        sum(case when column_b<>0 then time else 0 end) as columnbsum     from table     group by userid 	0.56996611845222
9387309	11038	sql order multiple data rows without combining the rows	select * from (   select      userid, msgid, null as postid, null as playerpostid, null as friendrequestid, timestamp   from messages   where userid=3   union all   select      userid, null as msgid, postid, null as playerpostid, null as friendrequestid, timestamp   from posts   where userid=3   union all   select      userid, null as msgid, null as postid, playerpostid, null as friendrequestid, timestamp   from playerposts   where userid=3   union all   select      userid, null as msgid, null as postid, null playerpostid, friendrequestid, timestamp   from friendrequests   where userid=3 ) as baseview order by timestamp 	0.000331904425426913
9408188	5471	merge two queries and return one of the possible values	select coalesce(t1.value1, t2.value2) as value from t1 inner join t2 using(id) where id=10 	0
9419929	24515	mysql combine two selects?	select o.user_id user_id, count(*) count from users o join users i on o.token = i.user_id where i.referrer is not null group by referrer order by count desc 	0.0399522462369234
9432683	39918	mysql how to join on same table including missing rows	select t1.id, t1.text as "enu", t2.text as "dan" from table as t1  left join table as t2 on (t1.id= t2.id and t2.language = "dan") where t1.langauge = "enu" 	0.000439537942029315
9440020	15160	select from result set using in	select rooms.title, rooms.room_number from rooms join room_user on     room_user.user = "bob" and     room_user.room_number = rooms.room_number 	0.0225462023209899
9441721	24171	sql count depending on another column	select count(*) as total, year from `videos` group by year 	0.000263404998578236
9451290	22794	phpmyadmin returns 0 rows in sql query	select * from status_votes where trim(vote) = 'like' and status_id = 1 and trim(item_poster) = 'lucase'; 	0.468459118244131
9456090	38035	select all data from a table which for the three ids that appear the most in another table	select * from team where teamid in (    select teamid from (       select teamid, count(workid)       from work       group by teamid       order by 2)    where rownum < 4); 	0
9457919	2437	how to efficiently count events on mysql	select        p.id               as photo_id     , p.user_id          as user_id     , count(f.photo_id)  as pre_faves_count from        photos as p   join       photos as allp           on allp.user_id = p.user_id   left join       favorites as f           on  f.photo_id = allp.id            and f.fave_timestamp < p.upload_timestamp  group by        p.id      , p.user_id 	0.011075888362962
9462573	1186	mysql group by multiple columns - unique listing	select distinct(flange_start) as flange from table1 union distinct select distinct(flange_end) as flange from table1 	0.00394145846813899
9470353	3461	mysql - using count(*) outside the select	select customer from customers group by customer order by count(*) desc 	0.0932257335363457
9475765	3569	getting rows with duplicate column values	select id from table group by id, rank having count(*) > 1 	0.000190874444213759
9486867	10611	mysql database resultset with values as close to a number "x" as possible	select * from tabs order by abs(`rated` - 3) asc limit 10 	0.0008678133701267
9525832	22377	limit results to n unique column values?	select a.name, b.something_random from table b     inner join (select distinct name from table order by rand() limit 0,50) a          on a.name = b.name 	0.000162792333768114
9531190	7617	transmitting sessions id from sql server to web scripts	select @@spid 	0.108558425700894
9533561	18885	core data function similar to the where='(sql query)'	select count(distinct headphones.id)  from headphones      inner join old_headphones on         headphones.id = old_headphones.id 	0.282952043492063
9547046	20999	group by quarter and month in sql server 2008	select [quarter], [month], sum([group]) as [group], sum([member]) as member,    sum([value]) as [value] from dbo.yourtablename group by [quarter], [month] 	0.0289363412811519
9553271	3947	querying multiple sql tables in a single statement	select  r.roomid,r.room, r.room_size,date_booked  from room  as r left  join room_booking  as rb on r.room_id=rb.room_id  where date_booked='$date' 	0.0473345346887327
9554238	29989	get updates from current user and all their friends - mysql query	select <columns> from (     select <columns>     from <friends criteria>     union     select <columns>     from <current user criteria> ) x order by msg_id desc limit 10 	0
9555207	36018	using left join to get total rows in other table	select (these columns should be in group by section), count(agr_col)  from table group by (here should be those columns also) 	6.51140560200861e-05
9555393	3058	(fast) searching in spite of row inheritance	select # if first table has no value, use parent table if(t1.col0, t1.col0, t2.col0) as virtcol0, if(t1.col1, t1.col1, t2.col1) as virtcol1, if(t1.col2, t1.col2, t2.col2) as virtcol2 from table as t1 left join table as t2 on t1.parent_id = t2.id left join table as t3 on t1.id = t3.parent_id # t3 would be children of t1. we don't want t1 to procreate. :) where t3.id is null # your actual search goes here: and virtcol0/1/2 = whatever 	0.0378961442954748
9560148	13823	sql - order by field in random numeric order	select mycolumn     from model  order by case when model.field1 = 'lexus'    then 0                when model.field1 = 'ford'     then 1               when model.field1 = 'toyota'   then 2               when model.field1 = 'mazda'    then 3               when model.field1 = 'mercedes' then 4 end, model.field2; 	0.0569343454735043
9564591	18692	database query limitation	select r.member_id, r.text      from review r, (select member_id, max(date) dat from review where text != "" group by member_id) t1           where r.member_id =t1.member_id and t1.dat=r.date     limit 2 	0.346863329055633
9566554	23471	how to add a single column php/mysql	select sum(course_unit) as total from your_table; 	0.00213270956633489
9567429	10511	how to find the exact years and days	select id,        [date-of-birth],        datediff(yy,[date-of-birth],getdate()) -                    case when dateadd(yy,datediff(yy,[date-of-birth],getdate()),[date-of-birth])>getdate()                    then 1 else 0 end as [no-of-years],        datediff(d,                 dateadd(yy,datediff(yy,[date-of-birth],getdate()) -                            case when dateadd(yy,datediff(yy,[date-of-birth],getdate()),[date-of-birth])>getdate()                            then 1 else 0 end,[date-of-birth]),                 getdate()) as [no-of-days] from ... 	0
9567815	9163	sql server last date	select      a.part,     a.partdesc,     sub.cost from     table1 a inner join     (select          b.part,         cost      from         table2 b      inner join         (select             part,             max(date) as maxdate          from              table2          group by             part) bb         on bb.part = b.part         and bb.maxdate = b.date) sub     on sub.part = a.part 	0.00361101843179257
9569648	24401	mysql- making use of the or statement	select requisition.reqnumber, staff.staffnumber, ward.wardname, itemname from requisition, staff, supply, ward, ward_staff, req_supply, nonsurgical, surgical where requisition.staffnumber = staff.staffnumber and requisition.reqnumber = req_supply.reqnumber and supply.ordernumber = req_supply.ordernumber and staff.staffnumber = ward_staff.staffnumber and ward_staff.wardnumber = ward.wardnumber and (supply.ordernumber = nonsurgical.ordernumber or supply.ordernumber = surgical.ordernumber); 	0.790097176496341
9580647	10213	how to use a full text index for exact matches?	select id from tblsearch where match ( title, brand ) against ("exact phrase") and  concat(title, ' ', brand) like '%exact phrase%'; 	0.399034627282984
9582218	26296	oracle rows to column transformation	select login_id      , sum(case when status_name='open' then count end) open      , sum(case when status_name='closed' then count end) closed      , sum(case when status_name='inprogress' then count end) inprogress      , sum(case when status_name='pending' then count end) pending from table group by login_id 	0.0426970845224313
9585719	15161	sql order by, group by, having	select r.candiate, r.result from results r inner join (     select candidate, max(post_time) as ptime     from results     group by candidate  ) r2 on r2.candiate=r.candidate and r2.ptime=r.post_time order by r.result 	0.550655540779971
9594014	24352	mysql reorder menu	select order from menu where id = :id; select id, order from menu where order = :existingorder + 1; update menu set order = order + 1 where id = :id; update menu set order = :existingorder where id = :existingid 	0.565026702534931
9609189	17216	t-sql merge pairs of rows with similar datetime	select t1.datetime, t1.filename, 'modified' as event from table t1 join table t2 on datediff(millisecond, t1.datetime, t2.datetime) < 500               and t1.event = 'deleted' and t2.event = 'created' union all select t3.datetime, t3.filename, t3.event from table t3  where not exists(select 1                   from table t4                  join table t5 on datediff(millisecond, t4.datetime, t5.datetime) < 500                                and t4.event = 'deleted' and t5.event = 'created'                                 and t3.id in (t4.id, t5.id) ) 	0.000238136282793881
9609295	16288	sql query, selecting data through 3 tables	select it_id, tp_name from item inner join type on type.tp_id = item.tp_id inner join [group] on [group].grp_id = item.grp_id where [group].grp_id = @groupid or [group].grp_name = @groupname 	0.0107118217389902
9614063	33796	search the sp's with the keyword	select object_name(id)      from syscomments      where [text] like '%youtext%'      and objectproperty(id, 'isprocedure') = 1      group by object_name(id) 	0.678494516468302
9617803	7382	avoid rows with null value from the result	select     blah having    user_count > 0 and    restaurant_count > 0     and order_count > 0; 	0.00164531001116598
9618800	6948	mysql: query for list of available options for set	select trim("'" from substring_index(substring_index(    (select trim(')' from substr(column_type, 5)) from information_schema.columns      where table_name = 'some_table' and column_name = 'some_column'), ',', @r:=@r+1), ',', -1)) as item from (select @r:=0) deriv1, (select id from information_schema.collations) deriv2 having @r <=     (select length(column_type) - length(replace(column_type, ',', ''))     from information_schema.columns     where table_name = 'some_table' and column_name = 'some_column'); 	0.00325714096105529
9624240	6612	how can i get the most recent date in sql?	select date from yourtable where  (     date = convert(varchar(10), getdate(), 101)     or     date in (select max(date)                  from yourtable                 where date!= convert(varchar(10), getdate(), 101)) ) 	0
9624968	15116	select random row per distinct field value?	select r.name,  (select r1.some_info from test as r1 where r.name=r1.name order by rand() limit 1) as     'some_info'  from test as r  group by r.name ; 	0
9631610	30078	mysql inner join 'unkown column'	select sql_calc_found_rows k_services.id, service_status, service_tourno, service_date, service_cxldate, service_difficultperiod, service_priority, service_currency, service_key_so, service_price_so, service_key_ok, service_price_cfm, service_supplement      from  k_services     join k_remarks on (k_remarks.remark_service = k_services.id and k_remarks.remark_type = 9)     where  k_services.service_market = 2      limit 0, 25 	0.614808931749942
9636011	41277	freetexttable query	select * from parts as ft_tbl  where ft_tbl.partno like '%164%' 	0.46185082725027
9644448	22932	combining mysql statement into 3 columns not 3 rows	select (select count(*) from p_a a inner join p_aa aa on a.id = aa.albumid where a.id = '04c9ed6e-1fb2-4d49-b5f6-a9d227ad7e7d'),        (select count(*) from _ph p inner join pa a on a.id = p.albumid where a.id = '04c9ed6e-1fb2-4d49-b5f6-a9d227ad7e7d'),        (select lastupdate from tsimestamp ats where ats.albumid = '04c9ed6e-1fb2-4d49-b5f6-a9d227ad7e7d'); 	0.0015022235233939
9652494	30519	get columns default values as they are a row of a resultset	select default( id ) , default( example )  from test limit 1 	0
9656258	41013	query to check booking availability by comparing datetimes	select c.*, b.starthire, b.endhire  from cars c join bookings b  where c.currentbranch = '$pickuplocation'  and not b.starthire between '$mysql_startdate' and '$mysql_enddate' and not b.endhire between '$mysql_startdate' and '$mysql_enddate' 	0.0538544753478085
9656883	12786	sql - get parent values based on id	select my.`name`, p.`name` as 'parent name', gp.`name` as 'grandparent name' from employee my  left outer join employee p on p.id=my.parentid  left outer join employee gp on gp.id = p.parentid where my.`id`=4 	0
9667039	33425	specify default value where no matching joined record	select r.role_name,        nvl( pr.person_name, 'vacant' )   from roles r        left outer join personroles pr            on(    r.role_id = pr.rold_id             and <<some date parameter>> between pr.start_date and pr.end_date) 	0.000164917969846039
9678039	26430	sql counting and average in one query	select     employee.ename     , avg(works.salary) as avgsalary     , count(company.cname) as numjobs from    employee left join     works       on employee.ename = works.ename left join     companies       on works.cname = companies.cname group by employee.ename 	0.00225773246949211
9680807	39252	select statement of mysql	select substring( column, 5, 4) from table group by 1 order by 1; 	0.219643015285764
9680856	32557	how to multiple aggregate from xmltype field within 1 sql?	select v.year, v.month, v.summonth,         sum(v.summonth) over(partition by v.year) sumyear   from (select x.year, x.month, sum(x.data) as summonth            from xmltest,                 xmltable('$d/cdata/r' passing xmldoc as "d"                    columns year integer path 'year',                           month varchar(3) path 'month',                           day varchar(2) path 'day',                           data float path 'data') as x           group by x.year, x.month) v 	0.00979311062205502
9691509	5121	t-sql : return variable amount of records based on the top value in a column	select a.* from table a, ( select col1,min(col3) as col3 from table group by col1 ) b where a.col3=b.col3; 	0
9698343	28311	how to select this table?	select     t2.data as from_date,     t1.data as to_date,     (t1.shows-t2.shows) as shows,     (t1.clicks - t2.clicks) as clicks from `market` t1     inner join market t2          on (t1.market_id=t2.market_id and t1.event='off' and t2.event='on' and t1.data>t2.data)     left join market t3          on (t1.data>t3.data and t3.event='on' and t3.data>t2.data) where t3.id is null 	0.270285635433893
9701994	26939	in jsp replacing the null value retrived from mysql database with "n/a"	select ifnull(country, 'n/a') from your_table 	0.0221023007488846
9707205	20334	calculate the time after converting into a new datatype	select round(cast( mins as float)/60,2) as [hour] from ( select datediff(minute, cast(starttime as time),cast(endtime as time)) as mins      from  data ) a 	0.000648342440494094
9709901	23782	how to turn sql query into sql function	select     @u1avg:=avg(r1.rating),     @u2avg:=avg(r2.rating),     @u1sd:=stddev(r1.rating),     @u2sd:=stddev(r2.rating) from mydb.ratings r1 inner join mydb.ratings r2     on r1.itemid = r2.itemid where r1.userid=1 and r2.userid=2; select (1/(count(r1.rating-1)))*sum(((r1.rating-@u1avg)/@u1sd)*((r2.rating-@u2avg)/@u2sd))*(count(r1.rating)/(1+count(r1.rating))) from mydb.ratings r1 inner join mydb.ratings r2     on r1.itemid = r2.itemid where r1.userid=1 and r2.userid=2; 	0.265481580313663
9713210	18182	how do i count the number of zeros in sql?	select sum(case when zeroorone = 0                  then 1                  else 0 end) as total_zeros   from table1 	0.000861662492679592
9728331	40923	mysql two fields in one table to select two result rows from additional tables?	select    t1.document1_id, t1.document2_id,    t21.document_title as t21_title, t21.document_description as t21_description,    t22.document_title as t22_title, t22.document_description as t22_description,    t31.document_filename as t31_filename,    t32.document_filename as t32_filename  from    table1 t1      inner join table2 t21        on t21.document_id = t1.document1_id      inner join table2 t22        on t22.document_id = t1.document2_id      inner join table3 t31        on t31.document_id = t1.document1_id      inner join table3 t32        on t32.document_id = t1.document2_id 	0
9730510	8548	if statement, modify output	select id, name, username, password, if (active >0, "yes", "no") from table_name 	0.695181689663174
9732467	25404	display the data from databse according to the difference in date in php	select other, stuff, timediff(departuredatetime, arrivaldatetime) as thedifference from mytable order by thedifference asc limit 0, 100 	0
9735389	13091	sql 2 counts with different filter	select     sum(case when coumnta < 0 then 1 else 0 end) as lessthanzero,     sum(case when coumnta > 0 then 1 else 0 end) as greaterthanzero from tablea 	0.00888836142892509
9744511	21164	getting data from a join in sql	select products.productname, [order details].orderid, [order details].qty  from products  inner join [order details] on products.productid = [order details].productid  where [order details].quantity = (select max(p.quantity) from [order details] p where p.productid = products.productid) 	0.027329509163248
9771156	13641	compare two db tables and hide existing items	select * from items where item_id not in (select item_id from orders); 	7.6318212160542e-05
9773236	5118	mysql - selecting closest row to a certain time on each day of a month	select       prequery.justthedate,       yt2.floatcolumnname    from       ( select               date_format( yt.timestampcolumn, '%y-%m-%d' ) justthedate,               max( yt.timestampcolumn ) as lastperday            from               ( select @firstofthismonth := date_format( '%y-%m-01' ),                        @firstofpriormonth := date_sub( @firstofthismonth, interval 1 month ) ) sqlvars,               yourtable yt            where                   yt.timestampcolumn >= @firstofpriormonth               and yt.timestampcolumn < @firstofthismonth               and hour( yt.timestampcolumn ) < 10            group by               `justthedate`            order by               `justthedate` desc ) prequery       join yourtable yt2          on prequery.lastperday = yt2.timestampcolumn 	0
9778194	19457	column title repeating in sql query?	select post_author, post_date, post_content, post_title, post_excerpt, post_status, comment_status, ping_status, post_password, post_name, post_modified, post_content_filtered, post_parent, guid, post_type, post_mime_type, comment_count from wp_posts inner join wp_postmeta on wp_postmeta.post_id = wp_posts.id where ( wp_postmeta.meta_key = 'internalonly' and wp_postmeta.meta_value is not null ); 	0.0344787260710616
9782948	18402	how to apply pagination to the result of show tables query in php	select table_name from information_schema.tables  where `table_schema` = 'my_db_name' limit 10 	0.00927989754224731
9785964	8183	mysql multiple subquery limit	select * from playlist where playlistid=$myplaylistid && playstatus=1 order by (likes-dislikes) desc, created asc limit 1 union  select * from playlist where playlistid=$myplaylistid && playstatus=3  order by (likes-dislikes) desc, created asc limit 1 union  select * from playlist where playlistid=$myplaylistid && playstatus=0 order by (likes-dislikes) desc, created asc limit 3 	0.600862424258709
9790173	3181	how to count using left join?	select     e.company,     count(l.leadid) as actions from     exhibitors as e      left join leads as l         on l.exhibitorid = e.exhibitorid         and l.contractorid = 100         and l.showid = "20120228ab" group by e.company order by actions desc limit 20; 	0.711636216977154
9794338	5447	counting rows from table after joins	select ph.pheed_id,     ph.user_id,     ph.datetime,     ph.repheeds,     ph.pheed,     fav.id,     fav.p_id,     fav.datetime as stamp,     u.username,     ava.avatar_small,     coalesce(pcc.count, 0) as comments_count from favourite_pheeds fav inner join pheeds ph on ph.pheed_id = fav.p_id inner join users u on u.id = ph.user_id inner join profiles pr on pr.user_id = ph.user_id left join user_avatars ava on ava.avatar_id = pr.avatar left outer join (     select pheed_id, count(*) as count     from pheed_comments     group by pheed_id  ) pcc on ph.pheed_id = pcc.pheed_id order by stamp desc  limit $offset, $limit 	0.00159415533397943
9795660	28593	postgresql distinct on without ordering	select distinct on (address_id) purchases.address_id, purchases.* from "purchases" where "purchases"."product_id" = 1 order by address_id, purchases.purchased_at desc 	0.16369241571533
9795921	6044	mysql query to get rows in a sphere (x, y, z coordinates)?	select x, y, z from reinforcements  where durability >= 1  and world=? and (pow((x-?),2)+pow((y-?),2)+pow((>-?),2))<pow(?,2) 	0.00206674994147226
9797279	28323	mysql join for items and tags	select t.item_id from tags t   join tag_names tn     on t.tag_id = tn.tag_id group by   t.item_id having   count(distinct t.tag_id) = (select count(*) from tag_names) 	0.0163027732907506
9800547	34119	multi column group in mysql	select vendor, tin, refno, pdate, sum(amt), vat, sum(vamt) from (select distinct  if(purchaseproduct_customerid=0,contactperson,vendorname) as vendor,  if(purchaseproduct_customerid=0,'',vendortinnumber) as tin, purchaseproduct_refno as refno, purchaseproduct_date as pdate, purchaseproductdetail_amount as amt, purchaseproductdetail_vat as vat, purchaseproductdetail_vatamount as vamt from vendor, vendordetails, invoice_purchase_product, invoice_purchase_product_detail where ( purchaseproduct_customerid=vendor.vendorid or purchaseproduct_contactpersonid=vendordetailsid ) and purchaseproduct_id=purchaseproductdetail_purchaseproductid) group by refno, vat; 	0.159056795740596
9827288	25638	mysql: how to select only users who signed up today	select * from user where date(from_unixtime(time)) = date(now()) 	0
9828027	21751	how can i return a substring based on charindex for starting and end points from a field in a table?	select substring(colname, charindex('txtstart', colname), charindex('txtend', colname) - charindex('txtstart', colname)) from htmltable ht where ht.date_ = '2009-01-01' 	0
9828273	9753	group and count in sql server 2008	select downloaddate, count(downloaddate) as totaldownloaded from yourtable group by downloaddate 	0.613912897596373
9828369	36809	taking max of a column based on certain criteria	select top 1 cap_price from  (     select sld_to_rnk, prd_id_rnk, max(cap_price) as cap_price      from sap_prod     where cap_price <> 0     group by sld_to_rnk, prd_id_rnk  ) as tmp order by sld_to_rnk, prd_id_rnk 	0
9829530	7320	how to eliminate and show only non-duplicate records (mysql)	select col1, col2 from table group by col2 having count(*) = 1; 	0.000282983149540989
9830165	27880	query to delete data from table names listed in a table	select * into #temp   from students.columns   where column_name like '%test' declare @column_name nvarchar(max) declare @table_name nvarchar(max) declare @sql nvarchar(max) while (select count(*) from #temp) > 0 begin   select top 1 @column_name = column_name, @table_name = table_name from #temp   set @sql = n'delete from ' + @table_name + n' where ' + @column_name + n' = @delete_key'   execute sp_executesql @sql, n'@delete_key nvarchar(max)', @delete_key = n'del'   delete #temp where column_name = @column_name and table_name = @tablename end 	0
9834758	1837	how to use two joins on the same column	select teams1.name as team1, teams2.name as team2, matchs.id, matchs.date, matchs.time from matchs     inner join teams as teams1         on teams1.id=matchs.team1     inner join teams as teams2          on teteams2ams.id=matchs.team2 	0.00338269200364031
9838548	35745	perform date range query from a single column control table (sql server)	select     * from     tableb b        inner join     tablea a        on           b.dateb >= a.datea        left join     tablea a_nolater        on           a_nolater.datea > a.datea and           b.dateb >= a_nolater.datea where     a_nolater.seq is null 	0.000529523243095902
9838657	23953	how to get another table column in my table?	select r.id, r.name, v.name from records r inner join villas v on v.id = r.vid where records.id = 5; 	0.000158985622775912
9846150	29480	how to check a distinct value exists (true/false) from the given multiple records in t-sql	select ref_number, service_numbers, service_type_code, opendate, currentappointdt, previousappointdt,   case max(case when lettert_created='true' then 1 else 0 end)     when 1 then 'true'     else 'false'   end from tbl where time_stamp between currentappointdt and previousappointdt group by ref_number, service_numbers, service_type_code, opendate, currentappointdt, previousappointdt 	0
9864446	36737	how to count records with newest date only	select count(distinct l1.leadid) as accepted from leads l1 left join leads l2 on l1.leadid = l2.leadid and l1.date < l2.date where l2.date is null and l1.`change` like '%ok%' 	4.70030404775131e-05
9866951	5074	sql query for select distinct with most recent timestamp first	select username, location, max(timestamp) from table1 group by  username, location 	0
9869055	18875	mysql datetime query to get values on the particular date	select date(createddate), sum(t.amount) from tablename t where date(createddate) =:createddate 	4.77329316849111e-05
9871076	38468	print date from timestamp value	select from_unixtime(`created_date`) from `users` 	8.78177114618398e-05
9873990	27966	round to .5 or 1.0 in sql	select round(2.2 * 2,0) / 2 	0.0191610348432873
9877872	763	mysql select sum of results with a limit	select sum(price) from (select items.price from items order by items.price desc limit 3) as subt; 	0.042127605941046
9877955	2133	mysql select non expired deals from one shop	select deal_name,min(price),shop from deals where date_format(expiration_date,'%y-%m-%d') >=curdate() $cat group by deal_name,shop order by deal_id asc 	0.0164726093502355
9891402	36120	filter sql data to get latest for each alternate id using mssql	select t.* from table t where isready=1 and t.id=(select top 1 t2.id           from table t2           where t2.isready=1           and t.thicknessid=t2.thicknessid           order by datetime desc) 	0
9899689	24979	sql query to read a user's stream	select a.* from social_activity_stream a inner join social_activity_stream b using(social_activity_id) where  a.social_actor_id = [user_id] and b.social_actor_id = [friend_id]; 	0.516053928807558
9907567	34135	(my)sql: select first number not taken in series of numbers, similar to max()	select t1.id + 1 from tbl t1 left join tbl t2     on t1.id + 1 = t2.id where t2.id is null order by t1.id asc limit 1 	0
9911742	31414	a single sql query to return as multiple tables in a dataset	select xxx, yyy from table1 select zzz, nnn from table2 	0.00254627830019434
9915278	30794	can you sneak an "insert" into a "select" statement?	select ... where x in (select f() ...); 	0.123085813937407
9919398	12042	start querying on a certain row criteria	select post_id,post_msg from table where post_id >= 3 order by post_id 	0
9921017	40647	sql inner join - retrieving wrong ids	select mc.id as movie_comment_id, mc.add_date, mc.movie_id, mc.comment, m.id, m.name  from movie_comment as mc  inner join  movie as m  on  m.id = mc.movie_id 	0.346544000359081
9924477	19959	how to count the number of duplicate records in a database?	select user_id, sum(count) from ( select user_id, text, count(tweet_id) count from tweets  group by  user_id, text having count(tweet_id) > 1 ) t group by user_id 	0
9928879	8634	sql query to get top rows until colname = 1	select * from mymessages where messageid > @messageid and messageid <=   (select min(messageid) from mymessages    where isweirdmessage = 1 and messageid > @messageid) order by messageid 	0.00024159571690269
9930560	35035	get same ids from detail table	select r.recipes_id from recipes r inner join recipes_pos rp on r.recipes_id = rp.recipes_id where rp.ingredients_id in (4, 6) group by r.recipes_id having count(distinct rp.ingredients_id) = 2 	0
9934846	9168	mysql query, selecting from 3 tables	select ids.leadid from     ids join     rlds on rlds.leadid = ids.leadid and recid = 999 and rdate > '03-20-2012' where ids.status = 'ok' union select leadid from pids where recid = 999 and change is not null and pdate > '03-20-2012' 	0.00332314316453053
9935690	3868	mysql datetime range query issue	select * from util_audit where `dated` between "2012-03-15" and "2012-03-31"; 	0.41997407739974
9938408	8582	mysql one to many relation with conditions	select event.*, eventvisibility.* from events as event      left join events_visibility as eventvisibility    on     (event.id = eventvisibility.event_id)     where     event.all = 1     or     (     eventvisibility.visible_to_id = 2 and      eventvisibility.visible_to = 159     ) 	0.0590333928049669
9951293	2063	mysql join with two columns looking at same table	select * from orders  join addresses collections on orders.collection = collections.addressid  join addresses deliveries on orders.delivery = deliveries.addressid where username=<username> 	0.000693425436084513
9953922	8725	relevance search across multiple related tables	select id,sum(relevance) as total_relevance from ( select      id,      (match(title) against ('search string')) as relevance     from cards union select      cards.id,     (match(brigade) against ('search string')) as relevance     from brigades      inner join cardbrigades on brigades.id=brigade_id     inner join cards on card_id=cards.id  union select      cards.id,     (match(identifier) against ('search string')) as relevance     from identifier      inner join cardidentifier on identifier.id=identifier_id     inner join cards on card_id=cards.id  ) as combined_search  group by id having total_relevance > 0 	0.0229600230555079
9966745	34777	mysql vertices & edges intersection	select * from edges e  join users u1 on e.name1 = u1.name  join users u2 on e.name2 = u2.name 	0.339438852877605
9971859	3700	(mysql) get 2x same table's collumn 1 result	select     u1.*,     u2.* from     friends     join users as u1         on friends._#id1=u1._id_     join users as u2         on friends.#id2_=u2._id_ 	0.00094520443568369
9975900	10562	mysql regex in where	select *  from `products`  where (products.name regexp '[[:<:]]wall[[:>:]]')   order by products.updated_at desc 	0.754473717819301
9983448	5771	how to show all results except the first one?	select * from table limit 10000000 offset 1 	0
9989029	4859	mysql cell values with dates as new columns with years	select     yourtable.city,     sum(if(year(created)=2009,1,0)) as '2009',     sum(if(year(created)=2010,1,0)) as '2010',     sum(if(year(created)=2011,1,0)) as '2011',     sum(if(year(created)=2012,1,0)) as '2012' from     yourtable group by     yourtable.city 	0
10007680	33784	sql have function	select first_name, count(link.job_id)  from employee, job, link  where  job.job_id = link.job_id  and employee.employee_id = link.employee_id and job.job_id in (select job_id from link group by job_id having count(*) > 1)  group by first_name  having (count(link.job_id) > 1 ) ; 	0.524289901180265
10013475	32637	select that returns list of values not occurring in any row	select test.number from test left join users on test.number = users.id where test.number<>users.id 	0.000292243881208241
10020468	38051	three table join issue with count	select xp.productid, count(xi.imageid) from xcart_products xp  inner join xcart_classes xc on xp.productid = xc.productid and xc.class = 'color' inner join xcart_class_options xco on xc.classid = xco.classid  inner join xcart_images_d xi on xi.optionid = xco.optionid group by xp.productid order by xp.productid desc 	0.745394550047568
10023463	29825	doing multiple sql queries in one query (aka saving doing two network round trips)	select (select person.id from person where person.name = 'james') as name,        (select country.id from country where country.name="china") as country,        (select location.person_id from location where person.id = location.id and country.id = location.country_id and person.name = 'james' and country.name="china") as location 	0.619830446905857
10027409	18137	mysql can't join two tables columns into one show	select show_users.id, count(distinct `table1`.id) as sum_fields , sum(`table2`.count) as count_all 	0.000243041790532479
10059685	12282	joining two tables with using value from left table	select t1.incid, t1.name, t1.sortby, sq.person,         if( t1.sortby=0, maxpoints, minpoints) pointsvalue from table1 t1 left outer join (     select incid, person, max(points) maxpoints, min(points) minpoints     from table2     group by incid ) sq on sq.incid = t1.incid where t1.category=@category order by t1.name asc limit 0 , 30 	0.000994750407984855
10071949	21526	combing these two mysql queries	select users.*,     sum(overtime_list.shift_length) as overtime_total,     (select group_concat(users_roles.role_id) from users_roles where users.user_id = users_roles.user_id) as roles from availability_list inner join users     on users.user_id = availability_list.user_id inner join `stations`     on `users`.`station_id` = `stations`.`station_id` inner join overtime_list     on overtime_list.user_id = users.user_id     and overtime_list.date >= '$totalovertimedays' where availability_list.date = '$date' and type = '$type' group by users.user_id order by overtime_total asc 	0.28450872200143
10081943	13575	display record between today's date and 6 months before	select * from loan_ledger where trandate between dateadd(month,-6,getdate()) and getdate()+1 	0
10082768	19844	get title of the latest record on a group	select t1.* from t t1 left join t t2 on t1.generated_id = t2.generated_id and t1.created < t2.created where t2.created is null 	0
10087963	12169	how can i do this in a single mysql query	select      u.id,      u.name,      count(p.product) as totalproducts,     sum(case when p.status = 'sold' then 1 else 0 end) as soldproducts from user u inner join product p on u.id=p.user_id group by u.id, u.name 	0.603141600130096
10096346	13703	how to write an "exclusive" query in sql?	select language from languages where language not in (     select language from languages l     join people p on l.country = p.country     where p.population <= 10^7) 	0.738999418639338
10109535	15247	tsql to return the dates of price changes from a price history	select ph.*  from      #pricehistory ph      left join #pricehistory ph2 on         ph.product = ph2.product         and ph.price = ph2.price         and ph2.date = (             select max(ph3.date)             from #pricehistory ph3             where                  ph3.product = ph.product                 and ph3.date < ph.date             ) where ph2.id is null 	0
10111955	32182	count messages per day before and after certain time and show in one resultset	select      user_id,      _date,      sum(_time <= '16:00') as before16,      sum(_time > '16:00') as after16  from messages  group by user_id, _date order by user_id, _date asc 	0
10126420	20164	mysql overlapping dates can't get it right	select a.datestart, a.dateend, a.agendaid, b.datestart, b.dateend, b.agendaid from agenda a, agenda b where  a.agendaid <> b.agendaid and b.datestart>= a.datestart and b.datestart<= a.dateend 	0.112010246653504
10128689	13738	sql - for each (if... then... else...)	select items.name  from items left join brands     on items.brand = brands.name where brands.name is null order by items.name 	0.00713974253013618
10141716	25609	dynamically list fields from a database table	select col.* from sys.columns col join sys.tables tab on col.object_id = tab.object_id where tab.name = @tabname order by col.column_id 	0.000373197495712531
10142915	12697	sql inner join between two tables	select * from (    select s.id,            case                when sa.date = '2012-01-01'               then 'absent'               else 'present'            end as status,           row_number() over (partition by s.id order by case when sa.date = '2012-01-01' then 1 else 2 end) as rownumber    from students s    left outer join studentabsentees sa on s.id = sa.studentid ) as a where a.rownumber = 1 	0.119866749997327
10145433	7273	sql find maximum then find occurances thereof	select e.employeeid,     sum(e.vacationhours + e.sickleavehours) as totalhours from humanresources.employee e  group by e.employeeid having sum(e.vacationhours + e.sickleavehours) >= all   (select sum(e.vacationhours + e.sickleavehours) from humanresources    group by employeeid) 	0.000136836458714183
10147878	17284	how to show all result from one table and check condition	select v.*, b.bid from table a left join table b on a.aid = b.aid and b.date > date_sub(curdate(), interval 1 day) 	0
10165823	3974	how do i get the top 1 value from a union of 2 columns?	select top 1 * from (   select column1 from table where column2 = 'whatever' and column3 = 'sure'   union   select column4 from table where column2 = 'whatever' and column3 = 'sure' ) r order by column1 	0
10170548	20513	how to reduce the float length	select round(cast(23 as float)/12, 2, 1) as total 	0.114599981651896
10170619	5069	how can i exclude left joined tables from top in sql server?	select * from   (select hbid as id, hbtitle, hbpublisherid, hbpublishdate, hbedid, hbeddate    from hardback    left join hardbackedition on hbid = hbedid    union     select pbid as id, pbtitle, pbpublisher, pbpublishdate, pbedid, pbeddate    from paperback    left join paperbackedition on pbid = pbedid   ) books inner join    (select top 10 *    from     (select hbid as id, hbpublisherid as publishedid, hbpublishdate as publishdate      from hardback      union       select pbid as id, pbpublisherid as publishedid, pbpublishdate as publishdate      from paperback     )    where publisherid = 7   order by publishdate desc   ) topten    on books.id = topten.id 	0.0029047392277778
10190684	14208	sql multiple counts, group by months	select case month(timestamp_iso(date))         when 1 then 'january'         when 2 then 'february'         when 3 then 'march'         when 4 then 'april'         when 5 then 'may'         when 6 then 'jun'         when 7 then 'july'         when 8 then 'august'         when 9 then 'september'          when 10 then 'october'         when 11 then 'november'         when 12 then 'december'     end as month,     count (case when defect = 'tv' then 1 end) tv,     count (case when defect = 'adsl' then 1 end) adsl,     count (case when defect = 'ip' then 1 end) ip from table where  status='closed' group by month(timestamp_iso(date)) order by month(timestamp_iso(date)) 	0.0153540139022702
10194067	8061	how to query a table (which has multiple rows pertaining to a single entity) and return grouped result but only where all conditionals have been met?	select user_id from some_table where user_id in (select user_id from some_table where (some_key = 'skill' and some_value='html')) and user_id in (select user_id from some_table where (some_key = 'skill' and some_value='php')) 	0
10197299	36582	mysql to display only the earliest of duplicates	select * from nodes n  join nodes nlater   on n.name = nlater.name    and n.reportedat < nlater.reportedat 	0
10197604	6365	sql distinct limitation	select distinct ltrim(rtrim(li_from)) from table 	0.219744743725817
10198862	36487	how do i insert data by selecting some values from another table	select           stock.id,       customers.id as expr1,       staff.id as expr2,       @vehicle_regno as expr3,       @order_details as expr4,       @total_price as expr5,       @order_date as expr6  from               stock   cross join      customers cross   join      staff  where           (stock.name = @stock_name)       and (customers.name = @customers_name)       and (staff.name = @staff_name) 	0
10199950	2775	count number of times value appears in particular column in mysql	select email, count(*) as c from orders group by email 	0
10206940	21959	a sql query from oracle	select column1,        column2   from <table> t1  where column2 in (select column2                      from <table> t2                     group by column2                     having count(*) > 1); 	0.192196441389076
10208708	18345	how to escape value keyword in mysql while using select statement	select compo.clecompo from compo compo on (compo.clecompo = metadatas_compo.clecompo) and ((metadatas_compo.`value` like '%%nom%%') or (metadatas_values.metavalues_name like '%%nom%%')) 	0.767238747189158
10209654	8398	displaying full datetime when sorting by hour	select  dateadd(hour, datepart(hour, timestamp), datediff(day, 0, timestamp)) [timestamp],         sum(totaloffered) [totaloffered] from    [my table] group by dateadd(hour, datepart(hour, timestamp), datediff(day, 0, timestamp)) order by [timestamp] 	0.0606788498002894
10216802	9484	pl/sql comparing tables	select distinct c.cid, j.jid  from candidate c, jobs j where j.sid=c.sid and not exists (select 'x' from jobs j2 where j2.jid=j.jid and j2.sid not in (select c2.sid from candidate c2 where c2.cid=c.cid)) 	0.0878290738270849
10230891	6830	how can i apply the limit statement in a sqlite query to a specific side of a join?	select oc.*, o.* from ordercontents oc inner join  (select *               from orders               order by id               limit 2) o on o.id=oc.id 	0.119256607510597
10233622	8262	using sum based on rowcount	select noa.noaid, noa.userid as clientuserid,  service.billingcode + service.mod1 + service.mod2 + service.mod3 + service.mod4 as billingcode, service.formtypeid, service.startdate, service.enddate, service.currentunits, service.adjustment, (     select coalesce(sum(datediff(second, a.start, a.[end]) / 3600), 0) as scheduledunits     from lel_scheduler_appointment a         inner join lel_scheduler_clientappointment ca on a.apptid = ca.apptid     where a.start between '1/1/2012' and '1/31/2012'         and a.[end] between '1/1/2012' and '1/31/2012'         and ca.clientid = noa.userid         and a.serviceid = formtypeid ) as scheduledunits from lel_noa noa     left join lel_service service on service.noaid = noa.noaid where noa.userid = 4     and service.startdate between '1/1/2012' and '1/31/2012'     and service.enddate between '1/1/2012' and '1/31/2012' order by clientuserid, billingcode, formtypeid, startdate 	0.00900262246832518
10241075	21989	mysql groupby in stages	select * from (      select id, type, type_id, content, match(content) against('john') as relevance, ifnull(parent_type, uuid()) as parent_type, ifnull(parent_id, uuid()) as parent_id      from mytable where match(content) against('john*' in boolean mode) group by parent_type, parent_id ) as search group by search.type, search.type_id desc  limit 10 ; 	0.680034917011748
10273987	26618	combine multiple queries different where clause	select a.store_number,a.gc_sold,b.total_cars from ( select        store_number, count_big(quantity_sold) as gc_sold from            invoice_detail_tb where        (invoice_date between convert(datetime, @startdate, 102) and convert(datetime, @enddate, 102)) and (jli_category_code = 'gc')                           and (invoice_detail_code like 'jlgc%') and (invoice_detail_type = 'item') group by store_number ) a, ( select   store_number,          sum(vehicle_count) as [total_cars] from     daily_sales_tb where    (operations_day between convert (datetime, @startdate, 102) and convert (datetime, @enddate, 102)) group by store_number ) b where a.store_number=b.store_number; 	0.120999586905621
10279351	29374	counting rows divided by conditions in one select	select b,count(*) as occurence from mytable group by b; 	0.000426562758832206
10281261	5834	retrieve data from two tables with indirect relation(from another table)	select t.* from territory t inner join region r on r.id = t.region_id inner join devision d on d.name = r.division_id where d.name = 'a' 	0
10283363	22801	mysql left joining same table twice	select     u.first_name,     u.last_name,     u.email,     (         select             sum(e1.total_vacation_hours_earned)         from             ee_calendar_events as e1         where             u.user_id = e1.sched_user_id     ) as vacation_hours_earned,     (similar) as absent_hours from     ee_all as u where     u.user_id = 23 	0.027375184945205
10284993	20813	mysql, procedure how to find a ships firepower	select numguns * displacement * displacement * displacement from classes where class = classname 	0.0536875886169772
10295649	4419	simple table join with access to joined table columns	select  partname, subpartname, subpartadded from    parts         left join         (   select  subparts.partid, subparts.subpartname subparts.subpartadded             from    subparts                     inner join                     (   select  partid, max(subpartadded) [subpartadded]                         from    subparts                         group by partid                     ) maxsubpart                         on maxsubpart.partid = subparts.partid                         and maxsubpart.subpartadded = subparts.subpartadded         ) subpart             on subpart.partid = parts.partid 	0.0925084181828112
10301150	13376	mysql merge two queries	select p.*, wpt.* from (select * from {$wpdb->prefix}terms as wpt1 where wpt1.name='$loc' limit 1) as wpt     , {$wpdb->prefix}most_popular as mp inner join {$wpdb->prefix}term_relationships wptr on (mp.post_id = wptr.object_id)  inner join {$wpdb->prefix}posts p on mp.post_id = p.id where 1=1     and ( wptr.term_taxonomy_id = wpt.term_id )     and p.post_type = '%s'     and p.post_status = 'publish' {$order} limit %d 	0.0230195580709422
10302541	36843	select from any of multiple values from a postgres field	select * from word_weight where word in ('a', 'steeple', 'the'); 	0
10312538	18803	sqlite - how to check if table exists before completing inserts?	select * from sqlite_master where name ='mytable' and type='table'; 	0.0620349558790557
10318272	33788	how to select from object type column in oracle 11g?	select id, treat(vehicle as truck).doors from vehicles 	0.0141864113498573
10322624	12399	merging two rows into one	select least(user1, user2), greatest(user1, user2), sum(count) as count from yourtable group by least(user1, user2), greatest(user1, user2) 	0
10327697	16658	find comma in oracle sql string	select       substr( colname, 1, instr( colname, ',') - 1 ) as p_1 ,       substr( colname, instr( colname, ',', - 1 ) + 1 ) as p_2     from yourtable 	0.0189184110268439
10330253	9514	joining with more parent tables	select type,code,total_count,type_11_14.name  from all_types_count  left outer join type_11_14       on all_types_count.type in (11,14)       and all_types_count.code=type_11_14.code       and all_types_count.code in ( 3456,6789)  left outer join type_12_15       on all_types_count.type in (12,15)       and all_types_count.code=type_12_15.code       and all_types_count.code in ( 2345,9087,234)  left outer join  . . . 	0.026229404570202
10331807	4411	mysql conditional table name in join	select      id,      name,      coalesce(trademark.name,design.name) as object_name from      opposition     left join trademark          on opposition.object_id =   trademark.id         and trademark.object_table ='trademark'     left join design         on opposition.object_id =   design.id         and design.object_table ='design' 	0.391897551648288
10334147	40168	calculate difference between rows with counter values in sql	select 1e0 * (cur.counter1 - prv.counter1)/(cur.unix_time_stamp - prv.unix_time_stamp)   as [value1] , 1e0 * (cur.counter10 - prv.counter10)/(cur.unix_time_stamp - prv.unix_time_stamp)      as [value10] , cur.counter1 as [cur_counter1], cur.counter10 as [cur_counter10], cur.unix_time_stamp as [cur_time] , prv.counter1 as [prv_counter1], prv.counter10 as [prv_counter10], prv.unix_time_stamp as [prv_time] from t1 cur, t1 prv where cur.counter1 = (select max(aux_0.counter1) from t1 aux_0) and prv.counter1 = (select max(aux_1.counter1) from t1 aux_1 where aux_1.counter1 < cur.counter1); 	0.000163035679318414
10338155	19727	ordering list of members closest to their next award	select s.user_id, s.user_name, s.user_score     , glc.gift_limit, glc.gift_amount from    (         select s1.user_id             , min( glc1.gift_limit ) as nextlimit         from score as s1             join gift_limit_count as glc1                 on glc1.gift_limit > s1.user_score         group by s1.user_id         ) as z     join score as s         on s.user_id = z.user_id     join gift_limit_count as glc         on glc.gift_limit = z.nextlimit order by ( gift_limit - user_score ) limit 10 	0
10349203	34849	wildcard of number in sql server	select spacename from spacetable where spacename like 'new[_]space[_]%' and spacename not like 'new[_]space[_]%[^0-9]%' 	0.1285289000064
10354917	33106	format date for sql query aggregating date	select     convert(date, tim) as timdate,     [g.tru] = sum(case when sec = 'tru' and typ = 'geo' then 1 else 0 end),     [g.loa] = sum(case when sec = 'loa' and typ = 'geo' then 1 else 0 end),     [g.sea] = sum(case when sec = 'sea' and typ = 'geo' then 1 else 0 end),     [r.sea] = sum(case when sec = 'sea' and typ = 'rte' then 1 else 0 end),     total  = count(tim) from ageo where src = 'ew' group by timdate 	0.0418733514743449
10358018	26004	mysql join two queries horizontally	select       week( tms.date ) as grpweek,       if( tms.org = "companya", targetsum.comptarget, 00000.00 )) as companyatarget,       sum( if( tms.org = "companya", tms.hours, 0000.00 )) as companyahours,       if( tms.org = "companyb", targetsum.comptarget, 00000.00 )) as companybtarget,       sum( if( tms.org = "companyb", tms.hours, 000.00 )) as companybhours    from       time_management_system tms          join ( select                        t.org,                       sum( t.target ) as comptarget                    from                        target t                    where                       t.org in ( "companya", "companyb" )                     group by                       t.org ) as targetsums             on tms.org = targetsums.org    where        tms.org in ( "companya", "companyb" )    group by       week( tms.date )    order by       week( tms.date ) 	0.327856165450175
10370585	4390	2 step sql query according to date	select `t1`.`cid` from        `tbl` as `t1`   join `tbl` as `t2` on (         `t1`.`cid`            = `t2`.`cid`     and `t1`.`campaign_id`    = `t2`.`campaign_id`     and `t1`.`date(datetime)` < `t2`.`date(datetime)`     and `t1`.`device`         = 'pc'     and `t2`.`device`         = 'iphone' ) where `t1`.`campaign_id` = @specified_campaign; 	0.00366803534563155
10377264	5319	how to find all rows that match every value given in filter criteria?	select user.* from user inner join user_role admins on admins.user_id = user.id and admins.role_name = 'admin' inner join user_role mods on mods.user_id = user.id and mods.role_name = 'moderator' 	0
10383941	13883	mysql show a test result based on the value of the field	select name, case sex                 when 1 then 'male'                 else 'female'               end from people 	0
10386107	9888	sql server - using sum of count	select  date,         cast((sum(case when isnumeric(q1) != 1 then 0                  when cast(q1 as int) >= 9 then 1                  when cast(q1 as int) <= 6 then -1                  else 0 end)         + sum(case when isnumeric(q2) != 1 then 0                  when cast(q2 as int) >= 9 then 1                  when cast(q2 as int) <= 6 then -1                  else 0 end)) as float)         / (sum(case when isnumeric(q1) != 1 then 0                    else 1 end)         + sum(case when isnumeric(q2) != 1 then 0                    else 1 end)) from    questions group by date 	0.122101589661711
10390707	35254	php mssql_query errors when converting date and/or time from character string	select    dbo.bsc.bsc_id,   dbo.bsc.bsc_name,    dbo.bsc.bsc_owner,    case maxview.maxdate      when null then null      else datediff(m,convert(datetime, left(maxview.maxdate, 4)+ right(maxview.maxdate, 2) + '01', 121),getdate())    end  from dbo.bsc  left outer join (select bsc_id, max(dbo.bscdataset.dateperiod) as maxdate  from dbo.bscdataset group by bsc_id) maxview  on dbo.bsc.bsc_id = maxview.bsc_id; 	0.487668925708292
10391235	1612	sql to group based on the counts of a column	select distinct   num_of_statuses = count(*),   count           = count(*) over (partition by count(*)) from atable group by id 	8.11419850784889e-05
10393846	916	how to select for the following in mysql?	select ... from accounts as a     join ownedaccounts as o         on o.accountid = a.id     join accounts as owner1         on owner1.id = o.ownerid     left join ownedaccounts as o2         on o2.accountid = owner1.id     left join accounts as owner2         on owner2.id = o2.ownerid where o.ownerid = ? 	0.104060531504543
10396331	28606	fetching a table with another tables "conditions"	select users.userid  from users join bodies on (users.emx = bodies.emx)  where ⌜true if bodies.text contains ?⌟ 	0.00250640318426184
10412472	24830	query for "how many users submitted content each month"	select count(distinct(t1.uid)) from node t1 inner join node t2 on t2.uid = t1.uid and t2.created between date_add(now(), interval -2 month) and date_add(now(), interval -1 month) inner join node t3 on t3.uid = t1.uid and t3.created between date_add(now(), interval -3 month) and date_add(now(), interval -2 month) inner join node t4 on t4.uid = t1.uid and t4.created between date_add(now(), interval -4 month) and date_add(now(), interval -3 month) where t1.created between date_add(now(), interval -1 month) and now() 	0
10420703	31094	order by twice within a column	select this_.person_id, family.value as family, given.value as given from person this_ left outer join name family     on this_.person_id = family.person_id     and family.part_type = 'family' left outer join name given_     on this_.person_id = given.person_id     and given.part_type = 'given' order by family.value, given.value 	0.0453451658230289
10430973	10908	sum of points per user greater than some value and ordered	select user, sum(points) as sum  from users  group by user  having sum > 300 order by sum desc 	0
10454508	10808	search in path which created by sys_connect_by_path in connect by prior query	select    group_id,  lpad('-',level,'-')|| group_name group_name,   sys_connect_by_path(group_name, '->')  group_name_path   from  groups  start with parent_id is null and type='g'  and group_id <> 24 connect by prior group_id=parent_id  and group_id <> 24 	0.2300999465515
10458473	2720	remove second appearence of a substring from string in sql server	select soq.practiceid,        case when left(soq.mystring, soq.slashpos) = substring(soq.mystring, soq.slashpos + 1, len(left(soq.mystring, soq.slashpos)))             then right(soq.mystring, len(soq.mystring) - soq.slashpos)             else soq.mystring        end as mystring   from (select oq.allfields, oq.mystring, charindex('\', oq.mystring, 0) as slashpos           from myoriginalquery oq) soq 	0.000511907427002951
10460532	6874	mysql subquery and having max value of subquery	select plaka,party_id, i  from (select plaka,party_id, sum(inf) i from party_sehir  group by  party_id, plaka) sum_group where (i,plaka) in ( select max(i), plaka  from (select plaka,party_id, sum(inf) i from party_sehir  group by  party_id, plaka) t1 group by plaka ) 	0.174796298463282
10482366	41035	mysql if in select	select d.id, d.type, coalesce(c.name, p.name) from debtors d left join companies c   on d.type = 'c' and c.debtor_id = d.id left join private_individuals p   on d.type = 'p' and p.debtor_id = d.id where d.id = 1 	0.186557413637696
10484327	6500	sql query results by year	select year(admit_date) as year_of_admit,   sum(case when gender='male' then 1 else 0 end)*100/count(*) as male,    sum(case when gender='female' then 1 else 0 end)*100/count(*) as female,    sum(case when homeless='yes' then 1 else 0 end)*100/count(*) as homeless from client group by year(admit_date) 	0.0648867506132504
10491631	29298	need to select all columns while using count/group by	select * from (select *, count(*) over (partition by dob) as numdob       from table      ) t where numdob > 1 	0.0100640678556572
10497897	11231	check that a db link is actually pointing to the right server	select property_value  from database_properties@<database_link>  where property_name='global_db_name' 	0.261009714286517
10499562	19086	limit query result by type	select distinct mm.mm_id, mm.mm_title, mm.mm_hash from boomla_multimedia mm,    boomla_multimedia_domain md  where mm.mm_id = md.mm_id and cat_id = 4 and md.dom_id = 26 and mm.mm_published = 1   and mm.mm_media_type = 'image' order by mm.mm_id desc limit 0, 2 union 	0.359507030972784
10507577	20169	matrix multiplication in python and mysql	select sum(price * exchange_rate) as total from sales left join (     select 'usd' as currency, 1.00000 as exchange_rate     union all     select 'eur', 1.32875     union all     select 'gbp', 1.56718 ) as exchange on exchange.currency = sales.currency 	0.677626514776008
10518413	4261	which is faster: "select * from table" or "select x,y,q from table" (from a table with 4 fields)	select x,y,z from table 	0
10527448	7429	how can i show a 2 column mysql composite primary key value as a default value in a 3rd column?	select col_1, col_2, concat(new.col_1,new.col_2) as col_3 from my_table; 	0
10530218	4115	mysql: left join and column with the same name in different tables?	select a.id, a.name, a.category_id, b.id as catid, b.name as catname from product as a left join category as b on a.category_id = b.category.id 	0.00143953501360226
10541830	35386	query to get last message only from all users	select a.from_user_id, a.message from table1 a where a.datetime = (select max(datetime) from table1 x where x.from_user_id = a.from_user_id) 	0
10546877	3104	getting data by maximum witheffect date	select slno, scxid, exid, cv,  max(witheffectdate)  from table1 where exid=35 	0.000915167476552873
10548476	35911	mysql query with multiple columns but exact matches?	select * from device_tbl where concat_ws(' ', manufacturer, model) = 'sony ericssonxperia arc'; 	0.012355476295916
10562889	8266	how to get last id if any column in sql server 2005?	select max(id) from mytable 	0
10566739	30529	how to select values that correspond with a max date in a mysql query	select r.`contract_id`,r.`start_date`, (select sub_r.`end_date` from `table` sub_r where sub_r.`contract_id` = r.`contract_id`  order by sub_r.`revenue` desc limit 1 ) as `end_date`, (select sub_r.`revenue` from `table` sub_r where sub_r.`contract_id` = r.`contract_id`  order by sub_r.`revenue` desc limit 1 ) as `revenue`  from `table` r group by r.`contract_id`; 	0.000635579909301948
10576033	34565	mysql join same table	select a.* from meta_date a left outer join meta_data b on a.post_id = b.post_id and b.meta_value = 'def' where  a.meta_value = 'abc' and b.id is null 	0.0332534300312703
10576435	33074	mysql - counting two things with different conditions	select      sum(if(name = ?, 1, 0)) as name_count,     sum(if(address = ? and port = ?, 1, 0)) as addr_count from      table_name 	0.00534087512398409
10598418	4830	sql query to find rows	select new_roll_no   from (select 'cd01 ' || to_char(rownum, 'fm0000') new_roll_no from dual          connect by level <= (select to_number(max(substr(roll_no, 6))) from t))  where new_roll_no not in (select roll_no from t)  order by 1 	0.0125000406530983
10606678	22661	mysql select against varbinary column	select *  from my_test_table  where col1 = left(sha1('test'),20); 	0.222784989718082
10611256	183	calculate time in postgresql	select * from some_table  where timestamp_column - interval '1 hour' <= 0; 	0.0281320005752255
10611518	26818	how to select available date slice	select number, room.price from rooms join room on room.rid = rooms.type  where rooms.type = ".$room_id." and rooms.number not in (     select number from reservation     where end >= from_unixtime(".$start.")     and begin <= from_unixtime(".$end.") ) limit 1; 	0.00347512308002886
10641627	34426	pulling data from a sql database table	select top 35 * from question_pool order by (newid()) 	0.00105490119048853
10645194	39865	sql sum a field grouped by same identifier in two different columns	select p.player id,        (select sum(qty) from tbl where win = p.player) win,        (select sum(qty) from tbl where lose = p.player) lose from     (select distinct win player from tbl     union     select distinct lose from tbl) p 	0
10646787	21091	select all users who have participated in all elections	select u.id as user_id, u.username from user u, (         select count(event_id) as event_count         from event         ) as e     inner join (         select udser_id, count(event_id) as event_count         from userevent         group by user_id         ) as ue on u.user_id = ue.user_id where e.event_count = ue.event_count 	0
10647059	11630	get all employees count whose first name starts alphabetically	select left(fname,1), count(1)  from employee group by left(fname,1) 	0
10649675	11861	how to query where multiple many to many relations are involved	select id,title,pub_cat.catid,pub_prog.progid,pub_type.typeid from publications inner join pub_cat on publications.id=pub_cat.pubid inner join pub_prog on publications.id=pub_prog.pubid inner join pub_type on publications.id=pub_type.pubid where pub_type.typeid=6 and pub_cat.catid=7 and pub_prog.progid=1; 	0.0453744424316806
10662648	10438	sql group by, convertion	select sum(sa.leavedays)/count(sa.leavedays),sa.status from     (         select cast(firsthalfstatus as float) leavedays,case when firsthalfleavetype=2 then 'paid leave' else 'medical leave' end as status,date         from staffattendance                 union all         select cast(secondhalfstatus as float),case when secondhalfleavetype=2 then 'paid leave' else 'medical leave' end as status,date         from staffattendance     ) as sa where month(sa.date)=month(getdate())    group by sa.status 	0.60570438808582
10662919	35150	sql query to get rows depending on month_year	select t.*,        (case when charindex('/', part1) > 0               then cast(left(part1, charindex('/', part1)) as int)              else 1         end) as month1,        (case when charindex('/', part1) > 0               then cast(substring(part1, charindex('/', part1), 100) as int)              else cast(part1 as int)         end) as year1,        (case when charindex('/', part2) > 0               then cast(left(part2, charindex('/', part2)) as int)              else 1         end) as month2,        (case when charindex('/', part2) > 0               then cast(substring(part2, charindex('/', part2), 100) as int)              else cast(part2 as int)         end) as year2 from (select t.*,              left(t.span, charindex(t.span, '-')-2) as part1,              substring(t.span, charindex(t.span, '-')+2) as part2       from t      ) 	0.000139197367820739
10663785	20051	hibernate - nonuniquediscoveredsqlaliasexception when two table has same column names	select it.id as itemid, nik.id as nikasaid from item it left join nikasa nik on (it.id = nik.item_id) 	0.000248740689743928
10670038	20765	how to combine a select query and a count(*) query?	select            c.cd,           c.c_id,           (select count(*) from  s where c_id = c.c_id and status = 'good') totals  from           f inner join s  on s.s_id = f.s_id            inner join c c on c.c_id = s.c_id  where     f.m_id = 2 and f.deleted = 'no'  group by  s.c_id  order by  f.update_datetime desc ; 	0.0330727189150037
10709430	32667	how do i change mysql output based on value	select user.user_name, queue.queue_name, queue_access.queue_access,        if(queue_access.queue_watch = 0, 'no', 'yes') from queue_access inner join user on user.user_id = queue_access.user_id inner join queue on queue.queue_id = queue_access.queue_id where queue_access <> '' or queue_watch = 1 order by user_name; 	0.00118926526481637
10710026	41273	count items grouped by different section names	select section, count(name) from table_name group by section 	0.000161887564329958
10710989	26342	how would i select the 1st, 12th, 68th or even 651st record with php?	select * from table order by rand() limit 1; 	0.0496013770578539
10723705	1772	float to date in mysql	select * from table where datefield = from_unixtime(rounded_unixtime) 	0.0525209991236024
10739936	13427	query return 1 row when no data present	select (case scanname when 'system-hq' then 'hq system' end) as system,  sum(case pspplmsseverity when 1 then 10 when 2 then 9 when  3 then 6 when 4 then 3 end) as score,  (sum(case pspplmsseverity when 1 then 10 when 2 then 9  when 3 then 6 when 4 then 3 end)/count(pspplmsseverity)) as  grade  from missingpatches  where scanname like '%system-hq%'  having system is not null # added order by last_update desc limit 1 	0.00137801454241601
10745205	24137	how to retrieve matching values from a single column in a table?	select id, avatar from mytable where replace(replace(avatar, '.resident', ''), ' resident', '') in (     select replace(replace(avatar, '.resident', ''), ' resident', '') as avatar     from mytable     group by replace(replace(avatar, '.resident', ''), ' resident', '')     having count(*) > 1 ) 	0
10752510	7583	select rows with 2 distinct columns	select   id,   val1,   val2 from (   select     *,     min(val1) over (partition by val2) as minval1,     max(val1) over (partition by val2) as maxval1   from atable ) s where minval1 <> maxval1 	0.000421994076529535
10769050	26504	sql select with grouping	select  m.* from    mytable m where   id = ( select   max(id)            from     mytable            where    ( sender_id = m.sender_id                       or recipient_id = m.sender_id                     )                     and ( recipient_id = m.recipient_id                           or sender_id = m.recipient_id                         )          ) 	0.310877801970743
10776519	1732	how to count and group query to get proper results?	select article_id, count(article_id) as votes from votes_table group by article_id order by votes desc; 	0.0737171552287003
10792703	253	mysql: avoid selecting columns with the same userid	select r.* from ringtones r      inner join (select min(id) as id, userid from ringtones                        where deletedbyuser='0' and (lang='$lang' or lang='en')                        group by userid) s     on r.id = s.id order by r.id desc limit 10 	0.00153377019200104
10804675	29060	optimizing specific sql query	select nationality, passport, airline, year(date_hour), month(date_hour), max(passenger), count(*) n_viagens from mastertable  group by  nationality, passport, airline, year(date_hour), month(date_hour)  having count(*) > 10 	0.678508197756211
10806415	9716	php/mysql most popular query syntax	select pageid, count(id) from views  where pageid== '22'  group by pageid  order by count(id) 	0.239432255432702
10813419	26587	sql joining for query	select provider_food_joints.*,         menu_item.*  from   provider_food_joints         inner join menu_item                 on menu_item.foodjoint_id = provider_food_joints.foodjoint_id  where  provider_food_joints.foodjoint_name = '".$foodjoint_name."' 	0.412858579529239
10822975	25710	send an email three days before eventstarttime	select * from events where date_add(curdate(),interval 3 days)=eventstarttime 	0.000918506144622437
10823420	28417	loop on xml with sql (xmltype)	select extract (column_value, '/record/field[@name="code"]/@value').getstringval () as code,        extract (column_value, '/record/field[@name="id"]/@value').getstringval () as id   from table (xmlsequence (xmltype (:xxml).extract ('/records/record')))  where extract (column_value, '/record/field[@name="id"]') is not null 	0.480441854134355
10828492	6891	convert time datatype into am pm format:	select convert(varchar(15),cast('17:30:00.0000000' as time),100) 	0.45070552073587
10843988	7435	issue in sql statement to get record combination using "in"	select d.empname, count(*) as total      from emp_departments d    where d.departmentname in ('dept1', 'dept2', 'dept3')  group by d.empname    having count(distinct d.departmentname) = 3 	0.162347927502015
10851569	5173	php/mysql tags query schema	select group_concat(tt.tagid) from topics t join tagtopic tt on tt.topicid = t.topicid where t.id=12 group by t.id 	0.169005557442431
10853722	13059	ms access/ms sql query	select * from fdetail  where      transactiondate >= #01/01/2007# and transactiondate <= #01/01/2015# and (         (comnum=1090084785010 and recid <> 24425)     or  (recid=32375 or recid=11174)     ) order by asc 	0.75538731937002
10855884	3315	pivoting data in mysql. 	select     s.name,     avg(r.result) as average,     t1.result as test1,     t2.result as test2 from     students s,     results r,     results t1,     results t2 where     r.student_id = s.id and     t1.test_id = 1 and     t1.student_id = s.id and     t2.test_id = 2 and     t2.student_id = s.id group by s.id; + | name | average | test1 | test2 | + | john |      70 |    90 |    50 |  | jane |    82.5 |    70 |    95 |  + 	0.404310436230321
10866816	35936	pulling in relational database fields	select   matches.match_id as match_id,   persa.name as persa_name,   persb.name as persb_name,   if(winner=person_a,persa.name,persb.name) as winner_name,   events.event_name as event_name from   matches   inner join person as persa on matches.person_a=persa.person_id   inner join person as persb on matches.person_b=persb.person_id   inner join events on matches.event=events.event_id where 	0.0349844484791585
10869731	14819	how to group ip list by subnet in mysql?	select     substr( ip, 1, locate( '.', ip, locate( '.', ip, locate( '.', ip ) + 1 ) + 1 ) - 1 ) as subip,    count(ip) as count from ip_list group by ( subip ) order by count desc ; 	0.0323955984689044
10871828	25339	query multiple tables but getting only the result from one table without duplicate	select    distinct invoice.* from invoice    left join contact on invoice.contact = contact.id    left join line on line.invoice = invoice.id where (   contact.name like '%search_term%' or    invoice.comment like '%search_term%' or    line.designation like '%search_term%' ) 	0
10877941	12954	how to get start date and end date of an event from end date	select event_id, event_name,    lag (event_end_date ) over (order by event_end_date asc )+1                                                          event_start_date,    event_end_date  from event 	0
10887431	9007	mysql join four tables and get some kind of sum result	select c.course_name, p.price_name, sum(cp.plan_time), sum(cp.plan_time * p.price_value) from courses c     inner join pricegroups p        on p.price_id = c.course_price_id     inner join course_to_plan cpl   on cpl.course_id = c.course_id     inner join courseplans cp       on cp.plan_id = cpl.plan_id group by c.course_name, p.price_name 	0.00660109258409917
10897068	37885	sql syntax for selecting the id column and latest date from two tables	select test_user_id, max(date_of_completion) as doc  from (       select test_user_id, date_of_completion from test_1_results        union all      select test_user_id , date_of_completion from test_2_results   ) as temptab  group by test_user_id  order by doc desc 	0
10898802	9549	sql count and floor	select floor(accountnumber) as [account number] from tblclientaccount where privatelabelseqid = 328 group by floor(accountnumber) having count(0) > 1 	0.296910476670799
10922124	11464	how do i select a date that is 4 days ago at this time?	select * from mytable where created_at > sysdate - 4 	0
10938145	35393	query columns names from a table from another user	select *    from all_tab_columns  where owner='anotheruser'     and table_name='the_table'; 	0
10952545	27620	the best way to get counts of occurrences	select nickname,count(nickname) from mytable group by nickname 	0.000129493906335833
10975595	34905	select birthday upcoming month	select birthdaycolumn from yourtable where month(birthdaycolumn) = month(getdate()) 	0.00083777488060132
10980870	9634	finding two person id which are there in both column	select     mytable1.id1, mytable1.id2 from     mytable mytable1,     mytable mytable2 where     mytable1.id1 = mytable2.id2     and     mytable2.id1 = mytable1.id2 order by     mytable1.id1 	0
10983746	7798	mysql - select statement that can name the results based on the condition	select     unix_timestamp(daystart) as yourdate , case      when daystart like '2012-06-11%' then 'today'      when daystart like '2012-06-10%' then 'yest'      when daystart like '2012-06-12%' then 'tomor'   end as daytype from daybook where userid = 1 	0.000445413226644945
10987192	5090	sql server analysis studio predicthistogram sort on adjustedprobability column	select topcount(predicthistogram([bayes].[code]), $adjustedprobability, 10) from [bayes]  natural prediction join    (select      (select 'michael' as [name]) as [name_table]   ) as t 	0.737745004465751
11000846	1740	mysql - select count below, equal or above in price table	select aux.date,        sum(aux.below) as 'below',        sum(aux.equal) as 'equal',        sum(aux.above) as 'aboce' from (    select t1.date,           t1.idproduct,           (select count(1) from tablename t2 where t2.date = t1.date and t2.idproduct = t2.idproduct and t2.price > t1.price and t2.idmonitor <> 0) as 'below',           (select count(1) from tablename t3 where t3.date = t1.date and t3.idproduct = t3.idproduct and t3.price = t1.price and t3.idmonitor <> 0) as 'equal',           (select count(1) from tablename t4 where t4.date = t1.date and t4.idproduct = t4.idproduct and t4.price < t1.price and t4.idmonitor <> 0) as 'above',    from tablename t1    where t1.idmonitor = 0 ) aux group by aux.date 	0.00792748075174786
11013090	33865	sql "group by" and "having"	select pc.hd from pc group by pc.hd having count(pc.hd) >= 2 	0.489288228349578
11014643	9313	tracking users - custom php/mysql website analytics	select count(url),url from   calllog where  calldate > now()-30days 	0.656532663165294
11015955	34637	mysql sql command to query from one table with three same columns to another table	select ticketnumber, issue, reporter.username, developer.username, manager.username from tickets  inner join users as reporter on tickets.enteredby = reporter.userid  inner join users as developer on tickets.fixedby = developer.userid  inner join users as manager on tickets.responsibleuser = manager.userid 	0
11022503	14647	mysql - table code and displaying content	select id, name, speed from records order by speed asc limit 10; 	0.0913993741560461
11024327	35045	need help joining a second table	select student_name,         city,         state,         request_date,         lat,         lng,         <<distance column>> as distance,         vendor.user_purchased from lesson_requests  inner join     (     select student_id, max(request_date) as max_request_date     from lesson_requests     where <<complex condition>>     group by student_name    ) as recent_student_lesson_request    on  lesson_requests.student_name = recent_student_lesson_request.student_name        and lesson_requests.request_date = recent_student_lesson_request.max_request_date left join vendor on v.user_purchased = lesson_requests.student_name where vendor.user_purchased <> 'abs_company'     and distance < blah; 	0.122565687620982
11026094	30112	select year/month format in a given interval of years	select d = replace(convert(char(7), d, 121), '-', '/') from  (   select distinct      d = dateadd(month, datediff(month, '19000101', coldate), '19000101')     from dbo.mytable     where coldate >= '20120101'     and coldate < '20140101' ) as x order by d; 	0.000152041847575065
11031588	29682	compare text values in postgresql	select <whatever>   from <your tables>  where one_field <> the_other_field    and position(the_other_field in one_field) = 1; 	0.0162589863199042
11036042	17301	combine multiple row in mysql query	select    i.id as invoiceid, i.userid, ii.invoiceid, i.duedate,    i.datepaid, i.setup, i.hosting, i.subtotal from   invoices i  inner join    invoiceitems ii on i.id = ii.id 	0.0182749095138926
11040423	39124	database query to find users that share an ip address	select columnip, count(*) from tableiplog group by columnip having count(*) > 1 	0.00052885026091222
11046484	35804	getting the rows which are in table1 but not in table2	select a.id,a.service,a.sub from @entry as a where not exists   (select b.* from @service as b where a.sub = b.sub and a.service=b.service) 	0.000197249803884342
11052340	609	mysql join and count query	select a.id, a.title, count(air.id) from advert a left join advert_interest_records air on a.id = air.advert_id group by a.id, a.title 	0.56254134097515
11056768	12105	pagination in oracle without specifying all columns	select *   from (select t.*,                row_number() over (order by column1 asc) rnk           from tablename t)  where rnk between 10 and 20 	0.0410422724658532
11058062	38165	how to replace a null when a count(*) returns null in db2	select a.ahshmt as shipment,  a.ahvnam as vendor_name,  coalesce( d.units_shipped, 0 ) as units_shipped, d.adpon as po,  coalesce( b.number_of_cases_on_transit, 0 ) as number_of_cases_on_transit,  coalesce( c.number_of_cases_received, 0 ) as number_of_cases_received from ... 	0.36424078132251
11071741	1189	querying multiple tables order by time in tables	select recipename, cook, timetocook, dated  from table1 union  select bookname, author, dated, null from table2 order by dated 	0.00898560721794415
11075690	14298	count number of unique users which loggedin more than once	select website.websitename, count(*) from website  inner join ( select userid, websiteid, count(*) from loginrecord group by userid, websiteid having count(*) > 1) as t1 on t1.websiteid = website.websiteid group by website.websitename 	0
11103821	25077	how can you format a persisted column as a padded integer string [sql server 2008]	select right('00000' + cast(id as varchar(5)), 5) + refnum 	0.066579563083098
11107922	14005	android sqlite fts3 create table if not exists	select distinct tablename from sqlite_master where tablename = ? 	0.651000191218197
11114224	20548	mysql ranking query	select r.*, @row:=@row+1 rank    from      (select u.user_id,r.totalvotes votes,r.totalpoints rating        from mismatch_user u           left join ratingitems r on u.user_id=r.uniquename     ) r     join (select @row:=0) pos  order by r.votes desc, r.rating desc 	0.58547049901354
11116028	9729	compare two tables's data in mysql	select a.id, a.services, a.statut     from manage_tcp a     where not exists(select b.id from manage_host b where b.id=a.id and b.statut=a.statut) union select a.id, (select services from manage_tcp where id=a.id order by id limit 1), a.statut     from manage_tcp a      group by a.id, a.statut having count(1)>1 	0.00450633651374955
11118319	13494	how to check if username exists	select count(*) from [user] where  username = @username and emailid=@emailid 	0.060245082097295
11137943	28232	convert rows into columns oracle	select 'select '||file_id||' file_id,'||   ltrim(sys_connect_by_path('rec_fld_'||field_number||' "'||field_name||'"',','),',')||   ' from response_details where file_id=' ||file_id||';'   from (select t.*,count(*) over (partition by file_id) cnt from response_metadata t)  where cnt=field_number start with field_number=1  connect by prior file_id=file_id and prior field_number=field_number-1 	0.00125199971521618
11158137	11000	parse sql server data	select   dbo.striphtml( yourtable.yourcolumn ) as yourresults from   yourtable 	0.495289400670804
11169925	21509	sql query / stored proc to count monthly average of daily sums	select yr, mon, avg(amt) from (select extract(year from tdate) as yr, extract(month from tdate) as mon,              extract(day from tdate) as day,              sum(iif(inout = 0, amount, -amount)) as amt       from pettycash       where tdate < '2012-01-01'       group by extract(year from tdate), extract(month from tdate),                extract(day from tdate)      ) t group by yr, mon order by yr, mon 	0.000666502430534839
11171127	28047	mysql select different	select t.* from table1 t join (select             max(id) as maxid    from table1    group by name,param) x on x.maxid = t.id where name='michael' 	0.0368982629128707
11173890	26455	eliminating null rows in tsql query	select [stuff] from  group_profile gp with (nolock)    inner join group_profile_type gpt with (nolock) on gp.group_profile_type_id = gpt.group_profile_type_id and gpt.type_code = 'fosterhome' and gp.agency_id = @agency_id and gp.is_deleted = 0    inner join group_profile mo with (nolock) on gp.managing_office_id = mo.group_profile_id    join payor_vendor pv on isnull(gp.payor_vendor_id, 'thisvaluewillneveroccur') = isnull(pv.payor_vendor_id, 'thisvaluewillneveroccur') ...etc... 	0.349169807287502
11175427	11001	mysql count rows in multiple date ranges?	select count(if(date >= date_sub(now(), interval 1 hour), 1, null)) as hourhits, 	0.000323900270779279
11183876	8121	mysql -selecting rows based on first three alphabets comparision of two columns	select * from tablename where left(columna,3)=left(columnb,3) 	0
11187106	3368	use different records from one table to combine it with the different entries of other	select e.emp_id,e.name,q1.qual_name,q2.qual_name, q3.qual_name from  employees as e inner join qualifications as q1 on e.qualification1=q1.qual_id inner join qualifications as q2 on e.qualification2=q2.qual_id inner join qualifications as q3 on e.qualification3=q3.qual_id 	0
11193639	11437	select distinct from muiltiple columns into one column	select columna from table union select columnb from table union select columnc from table 	0
11196643	17525	in mysql, how can i find all rows whose `attribute1` is the same as a particular row's `attribute1`?	select t1.id   from t as t1  join t as t2 on (t1.a = t2.a and t1.id <> t2.id) where t2.id=123; 	0
11205280	9013	how to count days present in values of a field	select count(distinct (cast (createdon as date))) as numberofdays from yourtable 	0
11221003	15580	does mysql accept order by "nothing" limit "all" when i only want to get number of results in a search query?	select count(*) from ... group by a, b, c having ... 	0.00583197955166278
11225821	7587	query selecting rows where data doesn't change	select     g.event,     min(g.selection) as selection_a,     max(g.selection) as selection_b from golf_matches as g group by g.event union all select     g.event,     max(g.selection),     min(g.selection) from golf_matches as g group by g.event order by 1, 2; 	0.0166371821767125
11233230	27610	sql query to return the result in one row	select a.a_id, a.b_id, a.a_desc, b.first_name, b.last_name,        coalesce(c1.address_type,c2.address_type) address_type,         coalesce(c1.city,c2.city) city,         coalesce(c1.state,c2.state) state from table_a a left join table_b b on b.b_id = a.b_id left join table_c c1 on c.b_id = b.b_id and c.address_type = 1 left join table_c c2 on c.b_id = b.b_id and c.address_type = 2 where a.a_id = 10 	0.00112709662856925
11238630	24278	mysql:while using group_concat & count	select  user_name,  group_concat(user_week) as user_weeks,   group_concat(user_reward) as user_rewards from (   select    user_name,    week(cpd.added_date) as user_week,    count(cpd.result) as user_reward   from cron_players_data as cpd    where    cpd.player_id = 81 and    cpd.result = 2 and    cpd.status = 1   group by user_week ) as temp group by user_name; 	0.586470033187536
11245989	30542	sql select query about grouping 2 columns	select     videos as 'number of videos',     count(user_id) as 'num of users' from (    select         count(distinct(topic_id)) as videos,         user_id from topic_user    group by         user_id  ) sub  group by     videos 	0.15332775760499
11249306	700	filling in the holes in the result of a query	select  isnull(sum(jan),0) jan,         isnull(sum(feb),0) feb,         isnull(sum(mar),0) mar,         isnull(sum(apr),0) apr,         isnull(sum(may),0) may,         isnull(sum(jun),0) jun,         isnull(sum(jul),0) jul,         isnull(sum(aug),0) aug,         isnull(sum(sep),0) sep,         isnull(sum(oct),0) oct,         isnull(sum(nov),0) nov,         isnull(sum(dec),0) dec,         a.rn bla from (  select *, rn=row_number() over(order by object_id)         from sys.all_objects) a left join cte b on a.rn = case when b.bla > 191 then 192 else b.bla end where a.rn between 1 and 192 group by a.rn order by a.rn 	0.0054776945357838
11254121	22461	oracle sql: how to show empty weeks / weeks without data?	select data.id, weeks.weekend_day, nvl(value, 0) value from (     select date '2012-01-01' weekend_day from dual union all     select date '2012-01-08' weekend_day from dual union all     select date '2012-01-15' weekend_day from dual ) weeks left join (     select 'a00' id, date '2012-01-01' weekend_day, 1 value from dual union all     select 'a00' id, date '2012-01-08' weekend_day, 7 value from dual union all     select 'b00' id, date '2012-01-08' weekend_day, 4 value from dual union all     select 'b00' id, date '2012-01-15' weekend_day, 3 value from dual ) data     partition by (data.id)     on weeks.weekend_day = data.weekend_day 	0.000363154877941342
11273605	11050	mysql - order a product table based on two column: discounted_price and price	select name, code, if(discounted_price=0,price,discounted_price) as real_price  from product order by real_price 	0
11276573	22736	determining free timeslots based on two tables in mysql	select workdays.date, count(distinct timebox.id) as freetimeboxes from workdays left join timebox on (weekday(workdays.date) = timebox.weekday) left join appointment on (workdays.date = appointment.date and timebox.id = appointment.timeboxid) where appointment.id is null group by workdays.date 	0.000207524723953628
11277251	30020	selecting distinct 2 columns combination in mysql	select id, col2, col3, col4 from yourtable where id in (     select min(id)     from yourtable     group by col2, col3 ) 	0.000318259961718227
11277478	40075	mysql query to return # of occurences for each distinct field	select id, count(id) as num_occurrences from table where status="pass" group by id 	0
11297239	40823	how to delete a default constraint from a table's column?	select *  from sys.default_constraints  where parent_object_id = object_id('luaffinity') 	0.000111696588210258
11302020	17912	combining two near identical mysql queries	select  users.userid,  targetedpackages.userid as targetedid, targetedpackages.timestamp as targetedtimestamp, targeterpackages.userid as targeterid, targeterpackages.timestamp as targetedtimestamp from  users inner join users as targeted on targeted.targetid = users.targetid inner join users as targeter on targeter.targetid = users.userid left join packages as targetedpackages on users.targetid = targetedpackages.userid and targetedpackages.timestamp = (select max(timestamp) from packages where packages.userid = users.targetid) left join packages as targeterpackages on targeter.userid = targeterpackages.userid and targeterpackages.timestamp = (select max(timestamp) from packages where packages.userid = targeter.userid) where users.userid = 2 	0.129869935873283
11306336	21554	mysql join - count matches on another table	select a.*, b.id as host_id,  sum(case when c.event_id is not null then 1 else 0 end) as count_joins,  sum(case when c.event_id is not null and c.user_id = 1 then 1 else 0 end) as joined from (`events` as a) inner join `users` as b on `b`.`id` = `a`.`host_id` left join `joins` as c on `c`.`event_id` = `a`.`id` where `a`.`date` > '1000-10-10 10:10:10' group by `a`.`id` order by `a`.`date` asc limit 20 	0.00310445415415724
11317790	28535	joining table with multiple fields in sql where one field needs to be summed	select dtable.trans_mbr, dtable.sum(base_amount) as dtable.sum_base_amount, code from (     select table_gl.trans_nbr, table_gl.base_amount, table_ap.code     from table_gl     left join table_ap on table_ap.trans_nbr = table_gl.trans_nbr     union     select table_ap.trans_nbr, table_ap.base_amount, table_ap.code     from table_ap ) as dtable group by trans_nbr 	0.00259656473935742
11321555	15391	mysql lookup ip address from another table with ip ranges	select avg(value1),avg(value2) from client_table c, ip_address_table ip where (inet_aton(ip) between inet_aton(starting_ip) and inet_aton(ending_ip)) group by date(date),hour(date) 	6.02969024991654e-05
11330066	27748	how can i get group count by sql with group by keywords?	select count(distinct postid) from `table` 	0.0630157896862469
11330871	37373	use modulo to calculate period?	select  course,         avg(timetocompletecourse) as avgtimetocomplete,         convert(varchar(4), ceiling(avg(timetocompletecourse) / 3.0) * 3 - 2)         + ' - ' +         convert(varchar(4), ceiling(avg(timetocompletecourse) / 3.0) * 3)         + ' months' as category from    yourtablename group by course 	0.0278606428667611
11335879	29155	change stored procedure based on input parameters	select * from yourtable where   (message = @query or @query is null) and     (forum = @forum or @forum is null) and     (username = @username or @username is null) and     (lastdate = @lastdate or @lastdate is null) 	0.0680220725845478
11354387	22360	can i use pure sql to return a range that includes one value less than the start value?	select * from movies where   start_time > 17 and start_time < 34   or start_time in (select max(start_time) from movies                     where start_time <= 17) 	0
11355634	26108	comparing two columns from different tables of different types in sql	select * from tbl1 except select      daterecorded,     schoolname,     studentname,     case isabsent when 1 then 'y' when 0 then 'n' end as isabsent,     case haspassed when 1 then 'y' when 0 then 'n' end as haspassed from tbl2 	0
11357844	19681	cross referencing tables in a mysql query?	select datatable.data,users.username  from datatable, users where users.id = datatable.genned_by 	0.709023391004758
11371871	5597	mysql how to grab more information with join?	select a.friend_id, a.pic_id  from table1 a    where exists (select 1 from table1 t            where t.pic_id = a.pic_id and t.friend_id = 84589) 	0.0352787103378679
11376267	15659	determining which columns to index in mysql in cakephp	select t1.name, t2.salary     from employee as t1      inner join info as t2 on t1.name = t2.name; 	0.0422819701197122
11386368	11703	sql query join with table	select table2.buyer_id, table2.item_id, table2.created_time, prod_and_ts.* from (select user_id, prod_and_ts.product_id as product_id, prod_and_ts.timestamps as timestamps       from testingtable2 lateral view            explode(purchased_item) exploded_table as prod_and_ts      ) prod_and_ts join      table2      on prod_and_ts.user_id = table2.buyer_id and         prod_and_ts.product_id = table2.item_id and         prod_and_ts.timestamps <> unix_timestamp(table2.created_time) union all select table2.buyer_id, table2.item_id, table2.created_time, prod_and_ts.* from (select user_id, prod_and_ts.product_id as product_id, prod_and_ts.timestamps as timestamps       from testingtable2 lateral view            explode(purchased_item) exploded_table as prod_and_ts      ) prod_and_ts join      table2      on prod_and_ts.user_id = table2.buyer_id and         prod_and_ts.product_id <> table2.item_id and         prod_and_ts.timestamps = unix_timestamp(table2.created_time) 	0.596336575897161
11387739	7270	compare two tables using sql join	select t2.buyer_id, t2.item_id, '*'+t2.created_time+'*' as created_time, t1.user_id, t1.product_id, '*'+t1.timestamps+'*' as timestamps from table1 t1     inner join table2 t2 on t1.user_id = t2.buyer_id     and t1.product_id = t2.item_id     and t1.timestamps <> t2.created_time union select t2.buyer_id, '*'+t2.item_id+'*' as item_id, t2.created_time, t1.user_id, '*'+t1.product_id+'*' as product_id, t1.timestamps from table1 t1     inner join table2 t2 on t1.user_id = t2.buyer_id     and t1.timestamps = t2.created_time     and t1.product_id <> t2.item_id 	0.0220283907913629
11390585	24942	max(date) - sql oracle	select * from    (select membship_id    from user_payment where user_id=1    order by paym_date desc)  where rownum=1; 	0.571612828988698
11390724	1148	placing two tables on data report in vb6? using msaccess	select a.slno, a.name1, b.name2  from table1 a  left outer join table2 b on b.slno = a.slno 	0.10039677613761
11410333	2879	select distinct and inner join a image data type	select * from customers where id in (select customerid from orders) 	0.128249771099386
11414034	37066	mysql query last updated row	select userid, coursename, grade from yourtable where userid = '8' and id in (     select max( id )      from yourtable     group by coursename ) 	0.000206821357258212
11424197	15788	mysql select a certain range using autoincrement id	select column1, column2 from table where columnid between 1000 and 5000 	0.000132682479881551
11443124	37897	how to select table and count other table	select     c.name,     (select count(1) from orders where id=c.id)  from     customers as c 	0.000524913024965596
11445445	30487	sql conditionally select different aggergates	select max(a) + case when (5 in (select a from t)) then 1 else 2 end as max_plus_something from t 	0.0302455629944363
11455360	30395	sql create a datetime from year and number fields	select cast(cast( incident_year as varchar(4)) + '-' +          cast(month_number as varchar(2)) + '-01' as datetime) as incident_year  from yourview 	0
11457060	10099	how to find differences between two queries that do not have a uniqueid	select (case when c3.uniqueaccountid is not null and t2.uniqueaccountid is not null              then 'match'              when c3.uniqueaccountid is not null then 'dev-only'              when t2.uniqueaccountid is not null then 'test-only'              else 'oops!'         end) as matchtype,        c3.uniqueaccountid as 'dev3', t2.uniqueaccountid as 'test2' from ctetest2 t2 full outer join      ctedev3 c3      on c3.uniqueaccountid = t2.uniqueaccountid and         c3.securityid = t2.securityid and         c3.buydate = t2.buydate and         c3.shares = t2.shares and         c3.buyprice = t2.buyprice 	6.91773814493303e-05
11458276	9189	retrieve two different fields for a joined table with repeated foreign key	select g.*,        'dose units' = (case when check_unit is null then du.unit_descr                             else concat(du.unit_descr+'/'+cu.unit_descr)                        end)  from groups g left outer join      units cu      on g.check_unit_id = cu.unit_id left outer join      units du      on g.drug_unit_id = du.unit_id 	0
11462971	5977	optimized sql query to count products in different tables that have reviews from the same user	select rp.pantid, rc.coatid, count(*) as cnt_pairs,        count(distinct rs.userid) as cnt_users from reviewshirts rs join      reviewpants rp      on rs.userid = rp.userid join      reviewcoats rc      on rs.userid = rc.userid where rs.itemid = <whatever> group by rp.pantid, rc.coatid 	4.8500749513225e-05
11482032	30512	find occurrence of a substring in string in mysql?	select from your_table where text2 like '%yourstring%'; 	0.000775661713891875
11491637	35237	select a single row with minimum column value - sqlite3	select * from (     select *     from zzz     order by a desc     limit x ) t order by b asc limit 1 	6.11294833592648e-05
11491828	38004	search multiple columns in two mysql tables?	select `id`,'profile_id' from  `profiles` as `p`  where `p`.`status` = 'active' and `p`.`address` like '%coupon%' or `p`.`businessname` like '%coupon%' or `p`.`businesssubcategory` like '%coupon%' or `p`.`descriptionme` like '%coupon%' or `p`.`tags` like '%coupon%' union all select `id`, 'productid' from `products` as `d` where `d`.`status` = 'approved' and `d`.`title` like '%coupon%' or `d`.`desc` like '%coupon%' or `d`.`tags` like '%coupon%' 	0.00278806734048265
11501190	26588	how to convert datetime to date in dd/mm/yyyy format	select  convert(varchar,a.insertdate,103) as converted_tran_date from table as a order by a.insertdate 	0.00215953264131674
11501724	24829	mssql: find records that has each value of column	select     value1 from      table as t1 inner join     (select distinct year from table) as t2     on t1.year=t2.year group by     val1  having count(distinct t1.year)=(count(distinct t2.year) ) 	0
11510855	31546	how to match in mysql	select distinct cs.cid, sj.jid from candidate_skill cs join skill_job sj on cs.s_code = sj.s_code where not exists(select 1                  from skill_job sj2                  where sj.jid = sj2.jid                    and not exists(select 1                                   from candidate_skill cs2                                   where cs.cid = cs2.cid                                     and sj2.s_code = cs2.s_code)) 	0.0769666225030596
11511232	37540	how can i make this query return results when one isn't present?	select st_transform(poly1.the_geom,3857) as the_geom_webmercator,         st_area(st_union(st_transform(st_intersection(f1.the_geom,poly1.the_geom),3857)))*.000247105381 as acreage_of_1,        st_area(st_union(st_transform(st_intersection(f2.the_geom,poly1.the_geom),3857)))*.000247105381 as acreage_of_2 from poly1 join      farmland f1      on f1.polygon_type = 'a' and st_intersects(fp.the_geom,poly1.the_geom) **left outer** join      farmland f2      on f2.polygon_type = 'b'  group by poly1.the_geom 	0.400981593719765
11523890	10682	null value handling	select     case         when val is null then 'valueisnull'         else 'valueisnotnull'     end     as newval from tbl 	0.494746384523171
11528554	24665	mysql query for team schedule	select    home.team_name as home_team,    visitor.team_name as visitor_team,    game_date,    if(       game_home_score = game_visitor_score,        'tie',        if(          game_home_score > game_visitor_score,          'hometeam',          'visitorteam'       )    ) as winner from game  inner join team home on home.team_id = game_home_team  inner join team visitor on visitor.team_id = game_visitor_team where game_home_team = ?  or game_visitor_team = 6  order by game_date asc; 	0.429027230405676
11537098	29710	mysql joining table on year condition	select      * from      tbl1 t join tbl2 on (right(tbl1.colname, 4) = right(tbl2.colname, 4) and instr(right(tbl1.colname, 4), '/') = 0) 	0.00331375057342293
11545995	23736	group by with conditional count	select      t3.displayname as [psi],      sum(case when t0.compliant = 0 then 1 else 0 end) as [failures],     sum(case when t0.compliant = 1 then 1 else 0 end) as [success] from lineitemsmap as t0     inner join art_blob as t1 on t1.art_blob_id = t0.blobid     inner join art_asset as t2 on t2.art_asset_id = t1.art_asset_id     inner join net_ou as t3 on t3.net_ouid = t2.net_ouid group by t3.displayname; 	0.675017085350842
11579946	37505	only show hours in mysql datediff	select timestampdiff(hour, start_time, end_time)             as `difference` from timeattendance where timeattendance_id = '1484' 	0.00065558187910577
11587708	9049	get next highest value and next lowest value from database	select min(number) as next_number from table_name where number > 6 select max(number) as last_number from table_name where number < 6 	0
11592503	1898	mysql check for 3 or more consecutive (specific) entries	select count(*) from `table`  where      id >          (ifnull(             (select id              from `table`              where `type`='login_success'              order by id desc              limit 1),0         )     and `type`='login_fail' 	9.45159725815686e-05
11600120	5443	mysql select statement returning no matches on one column	select * from judge where suburb like 'adelade%' or suburb like 'sydney%'; 	0.00490441532394191
11603614	30450	selecting in a where clause, inside a select statement	select user_name  from users  where user_name='$nick' and        password = md5(concat('$md5pass', md5(password_salt)))  limit 1 	0.691849411260222
11606234	17228	string replacement for formatting a name in mysql	select      case when instr(name, ',') > 0          then trim(concat(substring_index(name, ',', -1), ' ', substring_index(name, ',', 1)))      else name end as name_formatted from tbl 	0.794131885814672
11612925	21985	sorting username	select * from `members` where username like 'bx%' order by length(username), username 	0.333662422511213
11631128	6851	how to export a specific column data in mysql	select `column` from `table` into outfile 'file_name' 	0.00148617326071152
11636613	35123	mysql - select all unless query	select  oc_ieentry,oc_sysitem,oc_item,oc_itemdesc,oc_purchasedate,oc_url  from catalog  where (oc_purchasedate >= date_sub(current_date, interval 21 day))  and (oc_ieentry not like 1)  order by oc_item asc 	0.104964353366509
11636684	25755	mysql statment that can select the first non null or first integer value	select stuff from data  where convert(year, unsigned integer) >= 1990    and year != '-'  order by year  limit 1; 	7.654503278708e-05
11638602	25220	counting duplicates and removing them in mysql select statement	select class,count(1) "count" from cars group by class having count(1) > 1; 	0.0239283798021746
11643384	12704	converting sql to sybase dialect	select id from tablea  where typ_cd='nt'  and id not in ( select id from tablea where typ_cd='bb') 	0.655130516229288
11643833	34268	mysql counts from 3 tables	select u.*  from users u left outer join posts p on p.user_id = u.id left outer join comments c on c.user_id = u.id group by u.id having (count(p.id) + count(c.id)) >= 25 	0.0049135194808798
11650957	17791	sql server : sorting and checking	select name, kind, occur_time, value,        (case when max(testval) over (partition by kind, name) <> min(testval) over (partition by kind)               then 'fail'               else 'okay'         end) as status from (select *,              row_number() over (partition by kind, name order by occur_time, value) as seqnum,              (value - row_number() over (partition by kind, name order by occur_time, value)) as testval       from logs       where name='dude'      ) t   order by name, kind, occur_time, value 	0.540333148170324
11652265	40321	sql query: select all references after a specific item	select rs.* from ridestop rs join       (select ride, rs.sequencenumber        from ride r join             ridestop rs             on r.ride = rs.ride        where stationid = 8503000       ) r       on rs.ride = r.ride and          rs.sequencenumber >= r.sequencenumber order by rs.ride, rs.sequencenumber 	0.000146846703609837
11654632	18297	turning a wordpress post_meta table into an easier to use view	select p.post_title as post_title,          max(if(m.meta_key='phone_num',m.meta_value,0)) as phone_num,          max(if(m.meta_key='state',m.meta_value,0)) as state     from alpinezone_postmeta m     inner join alpinezone_posts p on m.post_id = p.id     where p.post_type = 'resorts'     group by m.post_id` 	0.478474015920724
11654956	15429	mysql database select issue	select * from (     select column_name*other_column_name as sqr     from table  ) x where x.sqr < 25  order by x.sqr; 	0.78210349971082
11656531	40867	how to combine between with timestampdiff using pdo query?	select *  from tmp where startedat < date_add(timestamp('2012-07-25 23:00:00'), interval 2 hour) and endedby >= timestamp('2012-07-25 23:00:00') order by startedat desc 	0.539957361174922
11660337	21952	get avg for this query	select date, avg(hourworked) as hourworked from  (     select date, sum(hourworked) as hourworked     from yourtable     group by employeeid, date ) t1 group by date 	0.609196638112124
11666633	17495	how to select maximum two values using limit in mysql?	select * from mytable order by salary desc limit 2 	0.000411385108500081
11683712	38185	sql group by and min (mysql)	select a.code, a.distance from   places a inner join (     select   code, min(distance) as mindistance     from     places     group by code ) b on a.code = b.code and a.distance = b.mindistance order by a.distance 	0.304082400544341
11692013	28052	mysql query count records with date in previous year	select count(id) as n  from table_name where datediff(curdate(), sell_date) >= 365; 	0.000129337013950577
11695803	12100	mysql sorting by date with group by	select * from (select group, max(date) as date from titles group by group) as x join titles using (group, date); 	0.176519164670706
11697665	37948	how to join two tables on common attributes in mysql and php?	select      table1.*,      table2.*  from      table2          right join table2          on table2.friend = table1.user  wehre      table2.user = 23 	0.000671069973742285
11708414	6623	mysql retrieving last record from table1 and join data from table 2	select b.*, c.name, c.device_name from   (select max(id) as id from trackers_data group by tracker_id) a join   trackers_data b on a.id = b.id join   devices c on b.tracker_id = c.tracker_id 	0
11721443	38730	picking timeseries from sql database in source priority order	select timestamp,        datapoint from (select t.*,              min(data_source) over (partition by timestamp) as mindatasource       from t      ) t where data_source = mindatasource 	0.0159351753619639
11721935	27530	mysql compare results 0 and 1	select (select 1) or (select 0) as result select (select 0) or (select 0) as result 	0.0241602614291503
11739017	25221	mysql - get count() for each row in a group with different condition	select scores.board, count(1) as position from scores join   (select board, min(value) as value    from scores    where deviceid = 1234    group by board   ) player_scores on scores.board = player_scores.board where scores.value < player_scores.value group by scores.board 	0
11762051	22120	using match and against in mysql and codeigniter	select `prod_id` from (`product_search`) where match (`prod_title`, `prod_desc`) against ('silk' in boolean mode) or `prod_id` like '%silk%' or `prod_sku` like '%silk%' or `prod_title` like '%silk%' or `prod_desc` like '%silk%'; 	0.220329426304329
11763897	30002	php converting string date and time to mysql datetime	select str_to_date(concat('08/01/2012', '09:41am'),'%d/%m/%y%h:%i'); 	0.0172300338570123
11767769	24818	mysql left join with multiple where columns	select *  from      customers  left join addresses  on        customers.cust_id = addresses.cust_id and       1                 = addresses.primary  where     customers.status = 1 	0.563531872195607
11771230	15202	php + mysql converting multiple rows into columns in a single row	select     t1.code,     t1.rate as buy,     t2.rate as sell from currency t1 join currency t2 on t2.code = t1.code and t2.trade_type = 'sell' where t1.trade_type = 'buy' 	0
11771806	37542	mysql query with counts or parental records	select r.id,count(v.id) from reviews r inner join visits v on r.id=v.review_id  group by v.review_id 	0.110248217221048
11794648	37406	converting timestamp to date in java	select *  from orders where status='q' and        date_format(from_unixtime(date),'%y-%m-%d') = current_date; 	0.0920473371195546
11797078	21927	getting individual values using group by - mysql	select  a.id,          a.plid,          a.zbid,         a.amount,          a.numbers,         c.totalamount from    lottery_winners a             inner join  (                             select  b.zbid,                                     sum(b.amount) totalamount                             from    lottery_winner b                             where   b.plid = 1                             group by b.zbid                         ) c                  on a.zbid = c.zbid where   a.plid = 1 order by    c.totalamount desc 	0.0139245682188524
11801696	36173	does constructor datetime take string or only timestamp type as parameter?	select * from alarms where alarmstate in (0,1,2)   and alarmpriority in (0,1,2,3,4)   and alarmgroup in (0,1,2,3,4,5,6,7)   and alarmtime like "2012/08/01%"   order by alarmtime desc 	0.0134357246470837
11802940	17007	access sql query to search value in 2 tables but use just one?	select  iif(isnull(afield),(select afield from table2 where id=16), afield) from table1 where id=16 	0.00927931794148906
11805836	10360	sql join multiple times?	select user_a.first_name as user_a_first_name, user_b.first_name as user_b_first_name, status.status_name from status left join users as user_a on user_a.id = status.user_from_id  left join users as user_b on user_b.id = status.user_to_id 	0.142197892218252
11828032	37335	mysql filter data by current date	select *  from demo_meeting where created_by_id in ( select id from demo_user where user_name = ' sang') and date(meeting_datetime) = curdate(); 	0.000905858971447986
11835454	628	how can i query the domain name with subdomains levels?	select * from table where domain_field like('%.%.%') 	0.093485281687739
11850515	1370	how to join top 1 quickly	select pkid, d.iddevice, d.idhardware, h.idrecorder, d.name, d.description, h.name as hardwarename, h.uri, r.hostname, r.name as recorderinstance, tbl2.collection_time, tbl2.raw_value, tbl2.calculated_value   from [surveillance].[dbo].[performancecounterinstance] pci   join [surveillance].[dbo].[devices] d on d.iddevice = (select replace(stuff([instance_name],1,charindex('[',[instance_name]),''),']',''))   join [surveillance].[dbo].[hardware] h on h.idhardware = d.idhardware   join [surveillance].[dbo].[recorders] r on r.idrecorder = h.idrecorder     outer apply     ( select top 1 *         from [surveillance].[dbo].[performancecountervalue]         where instance_id = pci.pkid         order by collection_time desc         ) as tbl2   where category_name = 'videoos recording server device storage'   and d.enabled = 1 	0.157559095833255
11853393	153	generating calculated fields by time period in report builder 3.0	select [year], [month], datediff(dd, cast(cast([year] as varchar) + '-' + cast([month] as varchar) + '-01' as datetime), dateadd(mm, 1, cast(cast([year] as varchar) + '-' + cast([month] as varchar) + '-01' as datetime))) as daysdifference from mytable 	0.0509210420557277
11872684	39563	get unique rows based on values and sort by time	select id, source, min(time) t  from table  group by source, id order by t 	0
11874188	37188	sql: getting the count of one table and join the others	select acount, b.id as id1, c.id as id2 from (select count(*) acount from table1 where value1 like 'certainvalue') a  left join table2 b on (b.name like '%userinput1%') left join table3 c on (c.name like '%userinput2%') 	0.000185722391382671
11875509	33785	mysql rank of more than one column of one user	select * from (select m.name,rank_level,rank_win  ,rank_loss from      (select @rank := @rank + 1 as rank_level,name,id from users order by level desc) m      inner join  (select @rankw := @rankw + 1 as rank_win,name,id          from users order by win desc) w on m.id=w.id      inner join  (select @rankl := @rankl + 1 as rank_loss,name,id          from users order by loss desc) l on m.id=l.id       , (select @rank := 0) m2,(select @rankw := 0) w2,(select @rankl := 0) l2 ) k where k.name= 'alan'; 	0
11878111	8313	fetch randomly record in php from mysql	select floor(rand() * count(*)) as rnd from your_table 	0.00011431546572778
11879887	3419	how to fetch multiple maximum records from the same column?	select max(bodyid) as bodyid,internaldocid, max(versionid) as versionid  from docbodyversion group by internaldocid 	0
11884310	23452	search with different privileges php	select i.*,c.*,cu.*u.* from items i,categories c, category_user cu, user u where i.title like '%$search%' and i.category_id=c.id and cu.category_id=c.id and u.id=cu.user_id and cu.role='expert' and i.visibility=1 	0.153712366730221
11894008	16147	how to get the "create table" query?	select (column_name + ' ' + data_type +         (case when character_maximum_length is not null               then '('+character_maximum_length+')'               else ''          end) + ','        ) as columndef from information_schema.columns order by ordinal_position 	0.00351932553187376
11898976	9804	cut mysql data when selecting	select  left(camera_name,length(camera_name)-2), max(camera_id) from cameras where site_id=1 group by left(camera_name,length(camera_name)-2) 	0.0804407336801403
11898994	35706	retrieve a random row for a group	select userid,picture from ( select userid, picture, row_number() over (partition by userid order by newid()) rn  from yourtable ) v where rn =1 order by xtype 	0.00042847092626217
11904634	3353	sql - group by unique column combination	select table.additionaldata, j.id, j.date from table inner join (select id, max(date) as date              from table group by id) as j  on j.id = table.id  and j.date = table.date 	0.0111209499423997
11906018	31011	optimize multi table search	select distinct p.product_id from cscart_products p      left join product_bikes pb on p.product_id = pb.product_id and pb.bike_id = 111     left join cscart_product_options po on po.product_id = p.product_id     left join cscart_product_option_variants pov on pov.option_id = po.option_id     left join variant_bikes vb on vb.variant_id = pov.variant_id and vb.bike_id = 111     where pb.bike_id = 111 or vb.bike_id = 111 	0.718700934221433
11906720	31521	obtaining one value per person from table ("latest-n-per-group before cutoff date")	select     b.* from     budget b     join (         select             therapist,             max(curdate) as maxdate         from             budget         where              curdate <= '2012-08-31'         group by             therapist     ) grouped on grouped.therapist = b.therapist and grouped.maxdate = b.curdate 	0
11908045	36849	count or bool of child records	select *, (     select (select case when count(*)>0 then 1 else 0 end as reccount      from listitems li3 where li3.listid = l.listid)      from lists l where li2.name = l.listname ) as haschildrecords  from listitems li2 where listid=1 	0.0027481118935754
11911508	23797	mysql: return top 16 results in random order	select * from  (     select * from your_table      order by rank     limit 16 ) x order by rand() 	0.0198795911182142
11919320	32096	mysql time comparisons	select * from tv_guide where curtime() between start_time and end_time; 	0.403342582156785
11924327	30153	multiply columns for currency exchange	select dollars * current_dollar_rate_in_rupees from tablename 	0.0505948705640578
11930694	2908	how to find albums using mysql query having 2 assets for each of its tracks	select    a.id,           a.name from      albums a join      tracks b on a.id = b.album_id left join (           select   track_id           from     assets           group by track_id           having   count(*) >= 2           ) c on b.id = c.track_id group by  a.id,            a.name having    count(*) = count(c.track_id) 	0
11934832	35504	sorting with sql	select km_ph_act_chapt_no from [km_db].[dbo].[km_ph_act_chapters]  order by convert(int, dbo.getintportion(km_ph_act_chapt_no)) ,    km_ph_act_chapt_no 	0.546705854581365
11935096	5056	vb.net comparing 2 databases	select t1.*, t2.* from table1 t1   inner join [;database=z:\docs\test.accdb].table1 t2  on t1.id=t2.id 	0.054874935648418
11939518	34213	parse string in sql	select  substring([stringtoparse], charindex('checkin: ', [stringtoparse])+9, charindex('< br/>',stringtoparse)-11) as checkin_date,         substring([stringtoparse], charindex('checkout: ', [stringtoparse])+10, len([stringtoparse])) as checkout_date from (select 'checkin: thursday, april 05, 2012 < br/>checkout: saturday, april 07, 2012' as stringtoparse      ) t 	0.425965006483126
11950031	3129	sql server 2008: select for update	select top (20) *      from [tma_not_to_entity_queue] with (updlock)     where [tma_not_to_entity_queue].[state_id] = 2      order by tma_not_to_entity_queue.id 	0.656561274101267
11952314	15796	how to select image data type with 'like' in mssqlserver	select * from dbo.tablename where convert(varchar(max),convert(varbinary(max), imagecolumn)) like @searchingword 	0.297812563982905
11953502	4952	how to calculate field data from 2x left join's	select `plant`.`plant_id`,     `qry1`.`total_hrs`,     `qry2`.`total_d`,     (`qry2`.`total_d` / `qry1`.`total_hrs`) as consumption from `plant` left join (     select (max(`plant_hrs_stop`) - min(`plant_hrs_start`)) as total_hrs,         `plant_id`      from`plant_hrs`     where month(`plant_hrs_date`) = month(current_date)     group by `plant_id`     ) as `qry1` on `plant`.`plant_id` = `qry1`.`plant_id` left join (     select (sum(`diesel_qty`)) as total_d,         `diesel_vehicle_no` as `plant_id`     from `diesel`     where month(`diesel_date`) = month(current_date)     group by `diesel_vehicle_no`     ) as `qry2` on `plant`.`plant_id` = `qry2`.`plant_id` order by `plant`.`plant_id` 	0.00907604641054963
11965847	12330	crosstab/cross over query	select school.sch_name school,   [£10.00], [£11.00],    [heads, deps], [relief bursar], [teaching staff] from (   select policyline.pli_pos_id,      policy.pol_own_id,      policy.pol_dcsf,      school.sch_name,      policyline.pli_premium,      coverpremium.cpr_premium,      staffcategory.sca_description    from school    inner join policy      on school.sch_own_id = policy.pol_own_id      and school.sch_dcsf = policy.pol_dcsf    inner join policyline      on policy.pol_id = policyline.pli_pol_id    inner join coveroption      on policyline.pli_cop_id = coveroption.cop_id    inner join  coverpremium      on coveroption.cop_id = coverpremium.cpr_cop_id      and policy.pol_own_id = coverpremium.cpr_own_id    right outer join staffcategory      on coveroption.cop_sca_id = staffcategory.sca_ ) x pivot (   sum(pli_premium)   for sca_description in([£10.00], [£11.00],                       [heads, deps], [relief bursar], [teaching staff]) ) p 	0.524314177239013
11966465	8446	select distinct values columna while columnb = value1 and columnb = value2	select content_id from tags where `name` in ('banana', 'orange') group by content_id having count(distinct `name`) >= 2 	0.282210613398918
11968533	24940	group between keywords tsql	select     f3.fruitname, f3.fruitcost, f.fruitname from     @fruit f         inner join     (         select  *,         (select max(productid) from @fruit f2 where fruitcost is null and productid<=f.productid) as fgroup         from    @fruit f     ) f3         on f.productid = f3.fgroup where f3.fruitcost is not null 	0.208967450828233
11970508	38975	how to do distinct by first column	select     wpg.id as id1,     min(wr.id) as id2 from     table1 wpg     inner join table2 wp on wp.wpgid = wpg.id     inner join table3 wr on wr.wpid = wp.id group by     wpg.id 	0.00153254507564508
11971745	8631	case statement for validating year	select id,   case     when extract(year from dt) between 1900 and 2050       then dt     else null   end as dt from db_table; 	0.531432048001264
11994440	16982	select distinct with a join and unnormalized tables	select tabl2.* from (select distinct id, name       from table1      ) join      table2      on table1.id = table2.id where table1.name = 'foo' 	0.189472502895719
12000537	6543	display parent count base on the grand-child	select      dc.category_id,     dc.name ,     count(ldc.name) as total from default_category as dc inner join default_category as ldc on ldc.parent_id= dc.category_id  inner join(select * from default_products where sale_wanted = 1) as dp on dp.subcategory_id = ldc.category_id where dc.parent_id = 0 group by dc.category_id 	0.000122993517852103
12003031	940	how to search by last id characters?	select * from users where cast(id as text) like '%123' 	0.000276154527171227
12007857	956	sql calculate days between two dates in one table	select t1.member_id,        datediff(day, t1.transfer_date, t3.transfer_date) as dd from yourtable as t1   cross apply (select top 1 t2.transfer_date                from yourtable as t2                where t2.transfer_date > t1.transfer_date and                      t2.member_id = t1.member_id                order by t2.transfer_date) as t3 	0
12017670	37252	compare string on range in sql server	select * from codelist where cast(substring(replace(fromcode,' ',''),3,len(replace(fromcode,' ',''))-4) as int) <= cast(substring(replace('iv2 1ab',' ',''),3,len(replace('iv2 1ab',' ',''))-4) as int)  and cast(substring(replace(tocode,' ',''),3,len(replace(tocode,' ',''))-4) as int) >= cast(substring(replace('iv2 1ab',' ',''),3,len(replace('iv2 1ab',' ',''))-4) as int) 	0.00366913932860359
12051687	3556	sql query for selecting data out of an table	select *,  left(sentrix_id,8) as prefix, iif(len(sentrix_id) = 8 ,"",mid(sentrix_id,10)) as suffix from table 	0.00439094183274856
12056336	30936	return multiple columns with a select max on only one	select func_status_code, name from (select func_status_code, name,              max(from_date) over () as maxdate       from table        where from_date <= current date      ) t where from_date = maxdate 	0
12056472	7100	unable to get total count in my query	select abb1.id, abb1.name,    totalcount =   (select          isnull(count(abb3.id), 0) as total      from          jfpmembers as abb4          inner join memberportfolio as abb3              on abb4.memberid = abb3.memberid      where          abb4.membershiptype = abb1.id           and abb4.isactive = 1          and abb3.isactive = 1)    from      membershipmaster as abb1      left join jfpmembers as abb2         on abb1.id = abb2.membershiptype     where      abb1.id <> 6  group by      abb1.id,      abb1.name  order by      abb1.name 	0.0131048295773977
12056821	5360	concat result from join	select    c.*   group_concat(s.nom) as `services` from client c   join uga u   on u.id_uga = c.id_uga   join appartenance a   on a.id_uga = u.id_uga   join serviceattribuee sa   on sa.id_client = c.id_client   join service s   on s.id_service = sa.id_service where a.id_utilisateur = 28 group by c.id order by ville_client 	0.159150914506629
12063632	14068	combining common values in mysql query	select distinct        (case when `emails`.`to` < `emails`.`from` then `emails`.`to`              else `emails`.`from`         end) as email1,        (case when `emails`.`to` >= `emails`.`from` then `emails`.`to`              else `emails`.`from`         end) as email2 from `emails` where ((`emails`.`from` = '".$loggedmember->id."')  or (`emails`.`to` = '".$loggedmember->id."')) and (`emails`.`to` != 0) order by `id` desc limit 4 	0.00842299501853938
12066123	18114	result set returns the default value in sql server 2008	select  temp.et  from    (             select  top 1                      row_number() over (order by eventtime desc) as id,                      eventcode,                      eventtime as et,                      status              from    cfw.dbo.dctbleventinfo               where   meterid = 4722              and     eventtime between convert(date,'2011-10-21') and dateadd(day,1,convert(date,'2011-10-26'))               and     eventcode = 13             order by eventtime desc         )   temp  where   status=1 	0.0520933695663711
12070316	38042	denormalize into pipe separated list	select cust, acc =      stuff((select '| ' +cast( acc as varchar(20))            from <table> b             where b.cust = a.cust            for xml path('')), 1, 2, '') from <table> a group by cust 	0.00546683564722054
12073592	10865	multiple count statements in 1 sql query without subselect	select user.id, user.name, count(distinct value_type_1.id),count(distinct value_type_2.id) from user    left join value_type_1 on user.id = value_type_1.user_id    left join value_type_2 on user.id = value_type_2.user_id group by user.id, user.name 	0.704550366859792
12080074	33154	select on records based on two column criterias	select table1.*  from table1, (   select count(*) as cnt, id   from (     select *      from table1     where type = 'a' or type = 'b'   ) sub1   group by id   having cnt > 1 )sub2 where table1.id = sub2.id 	0
12086985	4468	grouping mysql query contacts table by city	select  city, group_concat(name) from    contacts group by    city 	0.029641936082964
12093105	918	status table join for multiple states	select a.id, max(b1.date) status_date, sum(b1.status) latest_status,         b2.date latest_failure,        b2.total_failures from tablea a      left join tableb b1      on b1.aid = a.id      and b1.date = (select max(date) from tableb where aid = a.id)      left join       (select aid, date, count(*) total_failures from tableb where status > 0 group by aid, date) b2      on b2.aid = a.id      and b2.date = (select max(date) from tableb where aid = a.id and status > 0) group by a.id; 	0.0387753140751367
12098957	38984	php/sql voting and counting up the results	select carnum, sum(exterior+interior+engine) as score      from judge_votes      where catagory = '$catnum'      group by carnum 	0.0873064452066767
12101298	33946	group_concat a select statement	select group_concat(f.name) as `name` from (     select c.name as 'name',            count(sc.condition_id) as 'conditions_count'     from reviews r, strain_conditions sc     left join conditions c on sc.condition_id = c.id     where sc.strain_id = 1 && sc.review_id = r.id && r.moderated = 1     group by sc.condition_id     order by conditions_count desc     limit 3 ) f 	0.700030937212432
12104327	18035	select decoded json data from joined mysql tables	select * from trees join selectedtrees   on properties like concat('"id":"', trees.id, '"') 	0.00188984674379597
12114714	29271	finding duplicate rows in mysql (composite key)	select      transactiondate, purchaseorderid, count(*) cnt  from      purchases  group by      transactiondate, purchaseorderid  having      cnt > 1 order by      cnt asc; 	0.000684050901276514
12118068	9662	how do i pull both categories and tags from a mysql database for an item?	select    `items`.`name`,    `items`.`etc`,   group_concat(distinct `categories`.`name` order by `categories`.`name` desc separator ", ") as category,    group_concat(distinct `tags`.`name` order by `tags`.`name` desc separator ", ") as tag,    `items`.`id` as id  from `items`,    left join `item_categories` on `items`.`id` = `item_categories`.`item_id`   left join `categories` on `item_categories`.`category_id` = `categories`.`id`,   left join `item_tags` on `items`.`id` = `item_tags`.`item_id`   left join `tags` on `item_tags`.`tag_id` = `tags`.`id`  where `item`.`id` = $id group by `item`.`id` 	0
12150417	5461	sql query for multiple groups combining each group as an and statement and within each group as an or statement	select cp.entry_id from category_posts cp left outer join      group1 g1      on cp.cat_id = g1.cat_id left outer join      group2 g2      on cp.cat_id = g2.cat_id left outer join      group3 g3      on cp.cat_id = g3.cat_id group by cp.entry_id having max(case when g1.cat_id is not null then 1 else 0 end) = 1 and        max(case when g2.cat_id is not null then 1 else 0 end) = 1 and        max(case when g3.cat_id is not null then 1 else 0 end) 	0.000435222433194105
12155332	15316	how to convert the float datatype to string	select id,  isnull(convert(varchar(20),value), '-') as value  from table1 	0.0155598582227066
12160875	8419	sql query for post and replies	select *from post where post_id=1 or post_id in (select post_id from post_reply where parent_id=1); 	0.0853272082449627
12162236	23476	efficient mysql query/schema to store information coming from parallel processes	select a.id,        a.message as a_message,        (select b.message from b where b.id = a.id limit 1) as b_message,        (select c.message from c where c.id = a.id limit 1) as c_message from a 	0.243203169969543
12165999	3287	mysql union allow for non match	select     prod.pid, prod.manufacturer_name, prod.pupc, prod.pnum, prod.pprice, prod.psalesprice, prod.psalesdate, prod.psalesenddate, prod.psale,     group_concat(photoname) as photos from     ds_products as prod     left join ds_photos as pics on pics.objectid=prod.pid where    pics.photoflag =2 or pics.photoflag is null group by     prod.pid 	0.321050171743465
12166140	476	exclude sql with joins	select distinct m.idmovie, m.moviename  from movies m inner join moviespergenre mpg on m.idmovie = mpg.idmovie inner join genre g on mpg.idgenre = g.idgenre where m.idmovie not in (select idmovie from moviespergenre  where idgenre = 58) 	0.468363392577277
12184284	1775	sql design: finding rows that are not on a different table	select [cols] from header left join filters  on header_id=h_id where [filter col] is null 	7.62902117283167e-05
12185431	1029	select when value is not present in either of 2 columns	select * from exhibitors where  (email is null or email not in('email@email.com', 'email2@email.com'))  and (addlemail is null or addlemail not in ('email@email.com', 'email2@email.com')) 	0.000979590916491224
12186721	8728	convert four digit number into hour format sql	select {fn trim(leading '0' from left(col_name, 2) || ':' || right(col_name, 2)) } from table_name 	7.58954001994425e-05
12193445	35501	get rows with ids retrieved from other table, in the right order	select * from posts a       inner join       (          select item, cacheorder from cache as b          cross apply dbo.fnsplit(b.postids, ',')           where ((b.ownerid = 1) and (b.magid = 8))       ) v      on a.id = v.item order by cacheorder 	0
12216596	32080	a sql query which display name of area having max employees	select top 1 areaname from area     inner join employee      on area.areaid=employee.areaid group by areaname order by count(*) desc 	0
12219649	4694	count specific items in one column	select item_id, count(*) as count from ratings  group by item_id order by count desc; 	0.000117047803558256
12221463	19676	how to create an algorithm to suggest users	select * from tb_usario as a left join tb_ligacao as b on a.id = b.id_usuario_seguido where b.user_id = 1 	0.137892549394206
12225518	13070	calculating average of students' scores (with different coefficients)	select ([midterm score] + (2 * [final score])) / 3 as 'first course average' from #gradetable  group by [student id] 	0.0001335137503161
12242758	18135	how to display particular range values in varchar column in sql server 2000	select no,name,date from information where convert(date,[date],103) >=  convert(date,'25/08/2012',103)  and convert(date,[date],103) <=  convert(date,'01/09/2012',103) 	0
12245056	23236	joining 3 tables pgsql	select emp_num, first_name, last_name, amount from      table1         inner join table2 on table1.id = table2.table_1_id        inner join table3 on table1.table_3_id = table3.id where     effective_date between '2012-01-30 12:00:00' and '2012-03-01 12:00' and      acc_name = 'over pay' 	0.167431694735095
12245773	820	choose the greater of either left or right side of 2 queries	select top 1 from (      select top 1 m.sentdate as 'calltreelastsignedoff'    from incidents i    inner join plans p on i.planuid = p.uid    inner join incidentmessages im on i.uid = im.incidentuid    inner join messages m on im.messageuid = m.uid    where p.uid = '031e3346-2921-426e-9494-1111111111'    union   select top 1 m.sentdate as 'calltreelastsignedoff'    from incidents i   inner join planexercises pe on i.planexerciseuid = pe.uid   inner join incidentmessages im on i.uid = im.incidentuid    inner join messages m on im.messageuid = m.uid    where pe.planuid = '031e3346-2921-426e-9494-1111111111'  )a order by <col> 	0.0805744306117955
12256380	19936	how to add column value to sql like query?	select e.event,         e.params as params,         unix_timestamp(e.datetime) as datetime,         p.postid as postid,        q.postid as parentid  from qa_eventlog as e           left join qa_posts as p               on e.id = p.id                  left join qa_posts as q               on e.id = q.id         where  (date_sub(curdate(),interval 30 day) <= datetime) and         e.params like concat('%', 'postid=', p.postid, '%' )  and         e.params like concat('%', 'parentid=', q.postid, '%' )  and        e.userid = 1 order by datetime desc 	0.0253530540081653
12261985	24864	ordering with two tables	select * from table1  inner join table2 on table1.category_abbreviation = table2.category_abbreviation order by table2.category_name 	0.055751882155781
12266471	14831	join id names of one mysql table to ids in another	select i.clientcode      , c.name      , sum(i.sales)   from inventory i   left   join clientdetails c     on c.id = i.clientcode  where i.manufacturer='1'   group by i.clientcode, c.name  order by sum(i.sales) desc 	0
12290317	33360	how do you get the utc of a datetime field?	select   unix_timestamp(c.login_datetime) as `start` from   tbl_employees_login as c ; 	0.000513411522601424
12296490	20609	how to change logical disjunctive or sql query to conjunctive and to match all input parameters in list?	select v.id  from product_variant v       inner join product_variant_label_ref r on v.id = r.variant_id       inner join product_product p on p.producttype = :producttype       inner join product_label l on l.id = r.label_id       where v.product_id = p.id          and v.serviceprovider_id = :serviceproviderid          and l.label in (:labels)   group by v.id  having count(distinct l.id) = 3  	0.0368130010173747
12297324	22254	php mysql get data from 2 tables	select  ft.id,  ft.file_name,  ft.file_description,  ft.file_url,  af.id as access_id,  af.student_id,  af.file_id from  files ft  inner join access_files af on ( ft.id = af.file_id ) where  fa.student_id = '$studentid' 	0.000224407039973486
12309368	13969	how to get duplicate results in mysql output?	select st.name from students_id si join students_table st on st.id = si.id; 	0.00410664489613673
12315084	12238	aggregate totals from a result in mysql	select category_id, sum(amount) totalamount from tablename group by categoryid 	0.0539773221927417
12315738	21740	query for status change first time	select   c.cust_name from   customers_history c where   c.createddate = :yourdate and   c.cust_status = 1 and   not exists      ( select          'x'        from          customers_history c2       where          c2.cust_name = c.custname and         c2.cust_status = 1 and         c2.created_date < c.created_date ) 	0.00266302112287703
12316021	37905	return only first distinct row from each join	select      case arn when 1 then convert(varchar(10),aid) else '' end as aid,     case brn when 1 then convert(varchar(10),bid) else '' end as bid,     case crn when 1 then convert(varchar(10),c1id) else '' end as c1id,     c2id         from (                select a.id aid, b.id bid, c1.id c1id, c2.id c2id,     row_number() over(partition by a.id order by a.id,b.id,c1.id,c2.id) arn,     row_number() over(partition by a.id,b.id order by a.id,b.id,c1.id,c2.id) brn,     row_number() over(partition by a.id,b.id,c1.id order by a.id,b.id,c1.id,c2.id) crn            from a             join b              left join c1             left join c2  ) v 	0
12320007	4844	in oracle how to search with sub conditions on same column	select t1.car, t1.feature from yourtable t1 inner join (     select car, feature   from yourtable    where feature = 'feature1'     and exists (select car                 from yourtable                  where feature in ('feature2', 'feature3')) ) t2   on t1.car = t2.car where t1.feature in ('feature1', 'feature2', 'feature3')  	0.043291021749437
12322318	13826	sql query to return records with and without sub-records	select clients.id, clients.code, clients.name, commission.percent from clients left join commission on commission.clientcode = clients.code 	0.0423191674835177
12322342	40824	how to replace (null) values with 0 output in pivot	select class, isnull([az],0), isnull([ca],0), isnull([tx],0) from #temp pivot (sum(data) for state in ([az], [ca], [tx])) as pvt order by class 	0.343143171409499
12326605	28542	mysql order by second table	select p.pid, t.pname from properties p left outer join translations t on p.pid = t.pid     where p.hold=1 and t.isdefault='yes' and not exists     ( select * from translations ti where ti.pid = p.pid and ti.lang_id='en')     union select p.pid, t.pname from properties p      left outer join translations t on p.pid = t.pid     where p.hold=1 and t.lang_id='en'; 	0.00921424004512177
12344672	25651	count data depends on sentence id and frequency of data	select     a.*,      a.stem_freq * b.value from     tb_stemming as a     join      (         select             document_id,             sentence_id,             1 / sum(stem_freq) 'value'         from             tb_stemming         group by document_id, sentence_id     ) as b     on a.document_id = b.document_id and a.sentence_id = b.sentence_id 	5.26455402145647e-05
12347304	4890	sql joins to get monthly total wages from three tables	select  concat(first_name, ' ', last_name) ,       (         select  sum(hours*pay)         from    taxed_work tw         where   tw.employee_id = e.id                 and year(tw.date) = year(now())                 and month(tw.date) = month(now())         ) ,       (         select  sum(hours*pay)         from    nontaxed_work ntw         where   ntw.employee_id = e.id                 and year(ntw.date) = year(now())                 and month(ntw.date) = month(now())         ) from    employees e 	8.24322864567857e-05
12355127	8352	join mysql tables with three foreign keys to same table	select      d.*,      u1.name_full as head_user,      u2.name_full as assistant1,      u3.name_full as assistant2 from division_mst d      left outer join user_mst u1 on d.head_user_id=u1.user_id     left outer join user_mst u2 on d.assistant_1_user_id=u2.user_id     left outer join user_mst u3 on d.assistant_2_user_id=u3.user_id 	0.000189624740043479
12359116	4353	backtracking in sql	select company,        customer,        to_char(date, 'yyyy-mm') as month,        count(*) - (case                      when to_char(min(mindate), 'yyyy-mm') = to_char(date, 'yyyy-mm')                      then 1                      else 0                    end)   from (select t.*,                min(date) over (partition by company, customer) as mindate           from t) t   group by company, customer, to_char(date, 'yyyy-mm') 	0.380105665722904
12386129	19034	dividing the total number of documents by the number of documents containing the stem	select t1.doc_id, t2.token as word, t2.token_freq as df,  log(t1.docs/t2.token_freq) as idf from  (select doc_id,count(sentence_id) as docs from tb_sentence group by doc_id) as t1, (select distinct(stem) as token, doc_id, count(sentence_id) as token_freq        from tb_stem group by doc_id, token) as t2 where t1.doc_id = t2.doc_id 	0
12387061	2083	how to add column values in mysql	select *,(maths + chemistry + physics ) as total from `student` 	0.00327987615769324
12390261	25103	how to retrieve a value of an attribute from the xml stored across multiple rows using oracle-xquery?	select distinct  x.value as templatepartid,y.value as vid from  tempversion t , xmltable('/template/templateparts/template' passing t.content columns  value    varchar2(10) path '@id' ) x,   xmltable('/template/templateparts/template' passing t.content columns  value varchar2(10) path '@vid' ) y     order by templatepartid; 	0
12392755	27469	"select distinct" query bringing back too many unique rows	select      p1.c_clm,     p1.c_sta_clm,     p1.whse_curr_row_ind,     p2.loaded from pearl_p.tltc900_clm_prsst p1 inner join (     select max(whse_load_ts) as loaded, c_clm     from  pearl_p.tltc900_clm_prsst     where whse_curr_row_ind not in('y')     group by c_clm ) p2     on p1.whse_load_ts = p2.loaded     and p1.c_clm = p2.c_clm where p1.whse_curr_row_ind not in('y') 	0.0328931775151799
12395835	5235	selecting description based on 3 int columns	select id, department_code, sub_department_code, class_code,        (case when sub_department_code is null and class_code is null              then desc_text         end) as department_name,        (case when department_code is not null and sub_department_code is not null and class_code is null              then desc_text         end) as sub_department_name,        (case when class_code is not null then desc_text         end) as class_name from t 	0
12396464	1390	how to find all text blob fields in a firebird database	select   rf.rdb$relation_name,   rf.rdb$field_name from   rdb$relation_fields rf join rdb$fields f     on rf.rdb$field_source = f.rdb$field_name where   f.rdb$field_type = 261 and f.rdb$field_sub_type = 1 	0.000980375940310338
12396904	34582	sql - include multiple substrings?	select     case when <android-condition> then substr(uuid,1,17)          else substr(uuid,1,42)     end   , count(player_id) from play where trunc(create_dtime) >= to_date('2012-mar-01','yyyy-mon-dd') group by     case when <android-condition> then substr(uuid,1,17)          else substr(uuid,1,42)     end having count(*) > 5 order by count(player_id) desc 	0.109686012435036
12397184	30792	sql how to get player vs player game count from a games in a relational database	select count(*) as numofgames from ( select gameid,count(*) from  (     select gameid,playerid     from playersbygame     where gameid in     (         select gameid from gameinformation         where numberofplayer =2     )     and     playerid in     (         select id from players         where name in('dainon','andy')     )  ) as a group by a.gameid having count(*) =2 ) as b 	0.00429151589410347
12397493	12236	duplicate values returned from sql join statement	select am.*, tm.numtransactions from a01_accountmaster am join      (select accountnumber, count(*) as numtransactions       from t01_transactionmaster       group by accountnumber      ) tm      on am.accountnumber = tm.accountnumber where . . . 	0.00856480748002739
12405224	2320	substring sql nvarchar value from start to first non-int character	select left(columnname,patindex('%[^0-9]%', columnname+'a')-1) from table 	0.00043669540381029
12431737	3566	selecting parent rows with multiple conditions	select p.id, p.lname, p.fname,        (case when count(ct.indx) = 0 then 'none'              when ct.expirationdate is null or ct.expirationdate = '' then 'no expiration date'              when sum(case when activeflag = 1 then 1 else 0 end) = 0 then 'no active children'         end) as issue from parenttable p left join      childtable c     on p.id = ct.parentid group by p.id, p.lname, p.fname having (count(ct.[index]) = 0) or        (ct.expirationdate is null or ct.expirationdate = '') or        sum(case when activeflag = 1 then 1 else 0 end) = 0 order by p.lname 	0.00122068969572993
12449899	19709	returning a value even if no result	select ifnull( (select field1 from table where id = 123 limit 1) ,'not found'); 	0.0137506493741988
12452316	28558	category_ids to category in magento	select * from catalog_category_entity_varchar where entity_id = 40 	0.0540092169428068
12461194	23046	filter using a many-to-many table mysql	select   personid from   people_to_sports where   sportid in (1, 2) group by   personid having   count(*) = 2 	0.14921005953663
12492067	24662	join in two tables?	select m.*, g.picname from members m left join gallery g on g.member_id=m.id group by m.id 	0.0603706003842646
12497651	3413	postgres, checking if a set contains another set	select  c.product_id from categories c left join user_products up on up.product_id = c.product_id and up.user_id = 116 group by c.product_id having  sum (case when up.product_id is null then 0 else 1 end) = 0 	0.00230208285591598
12501864	14088	how to check if specific string exists in columns of different tables? (microsoft sql server)	select object_name(object_id, db_id('catastrophe')) from   catastrophe.sys.columns where  name like '%catws_energy_cb%'        and object_id in ( object_id('catastrophe.dbo.one'),                            object_id('catastrophe.dbo.two'),                            object_id('catastrophe.dbo.three') ) 	0.00013509501589506
12506610	20349	mysql select from select	select     date (a.created_at) as order_date,     count(*) as cnt_order from     `sales_order_item` as a where     month(a.created_at) = month(now()) - 1 group by     order_date order by     cnt_order desc 	0.0263453935624268
12520248	22302	sql random order by on joined table	select      idperson,      idquestion,     row_number() over (partition by personid order by ordering) as questionrank  from (     select idperson, idquestion, ordering      from person     cross join      (         select idquestion, newid() as ordering from question     ) as t ) as a order by personid, questionrank 	0.00919179673324496
12530127	21575	get many grouped values from mysql	select qq, q, count(*) from ( select 'a' qq, a q from test union all select 'b' qq, b q from test union all select 'c' qq, c q from test union all select 'd' qq, d q from test union all select 'e' qq, e q from test ) t group by qq, q; 	0.000140198866218427
12532962	20416	sql query - filter primary keys	select table1.a, table1.b, table2.c, table3.d from table1 t1 left outer join table2 on table1.a = table2.a left outer join tabl3 on table1.b = table3.b where not exists (select 1 from badtable where a = t1.a and b = t1.b) 	0.11382012215756
12549266	27998	select left/right join using where and return null's	select software.name as software,     device.d_id as pc_id,     device.name as name from software     left join device_software         on device_software.sw_id = software.sw_id        and **device_software**.d_id = 1     left join device         on device_software.d_id = device.d_id ; 	0.639451392280913
12580029	312	select record value based on date range	select table1.*, fyyear, fymonth from table1      inner join table2      on convert(date,convert(varchar(4),table1.year)+'-'+convert(varchar(4),table1.month)+'-'+convert(varchar(4),table1.day),120)     between table2.stdate and table2.eddate 	0
12585448	6290	need help in faster algorithm and code-checking - comparing values to database data	select exists(select atk_typ,pok_typ from mod_no where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ) union select exists(select atk_typ,pok_typ from mod_ne where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ) union select exists(select atk_typ,pok_typ from mod_av where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ) union select exists(select atk_typ,pok_typ from mod_se where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ) 	0.638615245658557
12610429	7479	postgresql: self-referencing, flattening join to table which contains tree of objects	select c.icount       ,c.acount             ,t.name       ,t.id as thing_id       ,t.city_id from  (    select t.city_id          ,count(nullif(a.active, 1)) as icount          ,sum(a.active) as acount    from   things t     left   join actions a on a.thing_id = t.id     where  t.city_id = 23               group  by t.city_id    ) c                              join   things t using (city_id) where  t.name ilike 'a%' and    t.datetime_at between '2012-09-26 19:52:14'                          and '2012-10-26 22:00:00' order  by t.name, t.id; 	0.0150755232959529
12615493	27832	how to generate xml with element and attribute using xml explicit	select         @domain "domain",        @name "name", ( select         id  "id",        value   "value",        (select          id "@id",         value  as "text()"               for xml path('record'), elements, type )        from   @testtable for xml path ('content'), type, root('contents') ) for xml path ('root') 	0.00975447123649392
12629815	8885	how to group by / group_concat each set of results?	select position,    group_concat(value order by overall_row_num) value from (   select position,       name,       value,       epoc,        @num := if(@position = `position`, @num + 1, 1) as group_row_number,        @position := `position` as dummy,        overall_row_num   from   (     select position, name,        epoc,        value,       @rn:=@rn+1 overall_row_num     from t1, (select @rn:=0) r     where name in ('a', 'b')     order by position, epoc   ) x   order by overall_row_num ) x1 where group_row_number <= 4 group by position 	0.00105639513564959
12644797	38265	calculate percentages with mysql/javascript	select m.refund_code, m.refund_amount, m.month_group, t.month_total  from (your refund query above) m  join (your total query above) t    on m.month_group = t.month_group 	0.474550960241909
12655529	15772	list only rows that appeared thrice in mysql	select a.activityid, a.title from activities a inner join deficiencies d      on a.activityid = d.activityid where d.status = 'cleared'     group by a.activityid, a.title having count(*) = 3 	0.00018957647700958
12678292	6185	earn the average of a row in a stored procedure in sql server	select aaa, bbb, ccc, ddd, eee, fff,     ((coalesce(aaa, 0) + coalesce(bbb, 0) + coalesce(ccc, 0) + coalesce(ddd, 0) +       coalesce(eee, 0) + coalesce(fff, 0)) /      ((case when aaa is null then 0.0 else 1.0 end) +       (case when bbb is null then 0.0 else 1.0 end) +       (case when ccc is null then 0.0 else 1.0 end) +       (case when ddd is null then 0.0 else 1.0 end) +       (case when eee is null then 0.0 else 1.0 end) +       (case when fff is null then 0.0 else 1.0 end)      )     ) as average from (     select          avg([aa ]) as 'aaa',         avg([bb]) as 'bbb',         avg([cc ]) as 'ccc',         avg([dd]) as 'ddd',         avg([ee]) as 'eee',         avg([ ff]) as 'fff'     from [fin] ) as averages 	0.0020683443554392
12679822	21110	how to determine the age of a person in atable	select *  from patientdetails  where datediff(current_date, str_to_date(p.dob, '%d-%m-%y'))/365 < 19 	0.00149912898955097
12690841	15557	mysql query select count	select  us.user_id, us.user_stalking_id, us.notification_viewed, u.id_user, u.firstname, u.lastname, u.logo_src, u.genre, us.id, us.date,      (select count(s.user_id) from user_stalking s where s.user_id = u.user_id) as stalking_count,      (select count(s2.user_id) from user_stalking s2 where s2.user_stalking_id = u.user_id) as being_stalked_count  from    users u, user_stalking us  where   us.user_id = ".$_session['user']['id_user']."      and us.notification_viewed = 0      and us.user_stalking_id = u.id_user order by us.date desc 	0.258775912375205
12691878	26008	wallposts and comments	select id, uid, site, text, date from comment left join comment_assign on (comment.id = comment_assign.comment_id) where comment_assign.assign_id is null; 	0.0800536691417797
12709573	31189	problems extracting statistics from a mysql table	select accesscode,         min(`in`) as first_in,         max(`out`) as last_out,         count(*) as exit_count,         sum(unix_timestamp(`out`) - unix_timestamp(`in`)) as seconds_attended  from my_table  group by accesscode 	0.0306996951637878
12711537	36958	select rows with a duplicate field based on another field	select m.* from mytable m inner join (     select model, max(char_length(category)) as maxlen     from mytable     group by model ) mm on m.model = mm.model and char_length(m.category) = mm.maxlen 	0
12716378	26619	how to join to one table, and fallback to another?	select     informants.name as ratname,    informants.type as rattype,    handlers.name as gmanname,    handlers.handlerid  from informants    left join handlers    on      (       (informants.type in ('politician') and (handlers.handlertype = case when exists (select top 1 1 from handlers where handlertype = 'cia') then 'cia' else 'fbi' end))       or         (informants.type in ('mob', 'famous') and handlers.handlertype = 'fbi')       or       (informants.type in ('citizen') and handlers.handlertype = 'police')       or       (informants.type in ('foreign') and (handlers.handlertype = case when exists (select top 1 1 from handlers where handlertype = 'nsa') then 'nsa' else 'fbi' end))     ) 	0.00288261321803505
12734020	38777	php date and mysql timestamp comparison	select ... where date(completed_date)='2012-10-03' 	0.0526937210697083
12739237	16376	sort the records in sqlserver with date( get the "n" latest added records from the table)	select top(5) *     from tbl order by created_date desc 	0
12759412	40901	extract string from another string in sql server 2008	select    replace(replace(reverse(left(reverse(yourcolumn), charindex('/', reverse(yourcolumn)) -1)), '>', ''), '"', '') from yourtable 	0.00200199588227803
12763100	17963	fetch mysql data with fitting string-end	select * from mytable where myfield like '%ly'; 	0.0325601350736892
12766758	12403	missing records when ordering rows by date	select * from bans order by to_seconds(date) desc limit 10 	0.00232035262549871
12788098	12214	query help – distinct records with max	select person, sport, max( date) as date        from activities       group by person, sport 	0.267662175995377
12790788	1973	changing sql query output depending on a column value	select name,id, '0' as budget, '0' as employees, '0' as duration from customers  inner join user_type on        customers.id = user_type.id where reg_date >= to_date( '01-sep-2012','dd-mmm-yyyy')     and reg_date <= to_date('01-oct-2012','dd-mmm-yyyy')    and user_type.reg_mode = 'normal' union select name,id, budget, employees, as duration from customers  inner join user_type on        customers.id = user_type.id where reg_date >= to_date( '01-sep-2012','dd-mmm-yyyy')     and reg_date <= to_date('01-oct-2012','dd-mmm-yyyy')    and user_type.reg_mode = 'privileged' 	0.00080875311994733
12818942	8154	how to create a table with date by range	select date_col, nvl(sum(t1.val),0) + nvl(sum(t2.val,0)) as sum from    (select to_date('01-oct-2012','dd-mon-yyyy') + level - 1 as date_col    from dual connect by level <= to_date('06-oct-2099','dd-mon-yyyy') - to_date('01-oct-2012','dd-mon-yyyy') + 1    ) d left join table1 t1 on (t1.date_column = d.date_col) left join table2 t2 on (some_t1_t2_join_condition and t2.date_column = d.date_col); 	0.000814407333436027
12819060	11792	distinct value is not coming in query	select name,id  from tbl_abc where name like '%william jam%' group by name 	0.204288883254609
12826797	26174	how do i put a conditioned count of a joined table in a separate column of the same joined table	select p.people_id         , p.company_id         , p.job_id         , b.bonus_id         , isnull((                    select count(pt.job_id)                      from bonus bt                 inner join people pt                        on pt.job_id = bt.job_id                     where pt.company_id = p.company_id                  group by pt.company_id                                   ), 0) as no_of_bonus_for_company      from people p  left join bonus b        on p.job_id = b.job_id 	0
12834145	40286	how to get the procedure call from a dmv in sql server 2008?	select  case           when r.statement_end_offset = -1 then              substring(s.text, (r.statement_start_offset / 2), len(s.text))           else              substring(s.text, (r.statement_start_offset / 2), (r.statement_end_offset /     2) - (r.statement_start_offset / 2))         end as statement_text       , q.query_plan       , r.cpu_time       , r.reads as request_reads       , r.writes as request_writes       , r.logical_reads as request_logical_reads from    sys.dm_exec_requests r         cross apply sys.dm_exec_sql_text(r.sql_handle) s         cross apply sys.dm_exec_query_plan(r.plan_handle) q 	0.0535470393528769
12842465	34785	return rows from right join that do not have matches	select d.*     from dest_table d     where not exists(select 1                          from src_table s                          where s.col = d.col) 	0.00360080869127701
12850893	9850	order by number of commas	select * from table order by length(areacodefield)-length(replace(areacodefield, ",", ""))) desc 	0.00317329329222777
12850937	35967	full join on two queries	select decode (a.id, null, b.id, a.id) as id, a.tvalue, countall, b.new, b.amend, b.cancel     from (select id ,sum(case when reason = 4 then 0 else quantity*price end)           as tvalue ,count(*) as countall           from table1           where date>=@startdate and date<=@enddate group by id         ) a full outer join         (select id , sum(case when reason = 1 then 1 else 0 end)              as new ,sum(case when reason = 6                            then 1 else 0 end) as amend ,              sum(case when reason = 5 then 1 else 0 end) as cancel             from table2 where date2 >=@startdate and date2<= @enddate group by id         ) b      on a.id = b.id 	0.293903276397551
12854911	26752	sql join for retrieving record for a single user	select      cur_doctor_names.first_name,      cur_doctor_names.last_name,      w.website  from      cur_doctor_names          left join cur_website as w          on cur_doctor_names.userid = w.userid  where          cur_doctor_names.userid = 69 	0.000939520420235478
12856659	23383	check sequence in max min values	select prev.tbproduct_id,prev.maxquantity   from yourtable prev   left join (select tbproduct_id, max(maxquantity) maxquantity from yourtable group by tbproduct_id) maxes     on maxes.tbproduct_id=prev.tbproduct_id and maxes.maxquantity=prev.maxquantity   left join yourtable next     on next.tbproduct_id=prev.tbproduct_id and next.minquantity=prev.maxquantity+1   where maxes.tbproduct_id is null and next.tbproduct_id is null; 	0.00497012660695564
12858996	23133	sum multiple rows	select `table`.`id`, `mod`, mysum from `table`  join (select `id`, sum(n1) + sum(n2) + sum(n3) as mysum         from `table` group by `id`) as grptable on `table`.`id` = `grptable`.`id` 	0.0126459246941832
12863285	5337	mysql query if condition	select a2_comp.*, a2_deal.* from   a2_deal natural join (   select   companyid, max(servertime) as servertime   from     a2_deal   group by companyid ) t join a2_comp using (companyid) 	0.470662772211225
12872306	12157	query to group and create a group total	select country, count(*), sum(views) from tablea group by country 	0.0116207178618447
12880797	26828	mysql, select rows according to date	select * from my_table where date >= '2012-10-14' order by date limit 5 	0.000647543022931103
12886295	8984	sql sum some column when all other columns match	select      t.catalogid,      sum(t.numitems) as numitems,      sum(t.ignoreditesm)  as ignoreditesm from ##temporderstable t group by      t.catalogid, t.supplierid, t.cname, t.cprice,      t.cstock, t.ccode, t.minstock, t.pother4 	4.55521037353393e-05
12893833	11396	how to fetch record monthly total in select query in sql server 2005	select * from (     select number, datename(m,dateadd(m, number-1, 0)) as monthname      from master..spt_values      where type='p' and number between 1 and 12 ) months     left join (your totals query) totals     on months.monthname = totals.month 	6.26608335288995e-05
12895106	33625	add results of one sql query to another query	select person_ref from images where effect_ref = 2 and person_ref in  ( your first query which gives 2 4 5 6) 	0.0017684855294154
12903548	39612	using avg() in oracle sql	select * from student where age > (select avg(age) from student) 	0.75810505376913
12911526	10168	any way to select from mysql table where a field ends in certain character/number?	select ...   where somefield like '%1' 	0.000108976824608196
12928000	14997	mysql subquery select specific column	select * from table_a where id = (select id from  (select a,id,b from table_b limit 1)a); 	0.0575583249492857
12930279	15901	count query in db2	select t1.ap_nbr, count(distinct t1.loc_nbr), count(distinct t2.itm_id) from tab1 t1 join tab2 t2 on t1.loc_nbr = t2.loc_nbr group by t1.ap_nbr 	0.38274366293425
12938337	30818	combining results of multiple subqueries in one set	select * from table3  where id not in (     select id from table1      union all     select id from table2  ) 	0.0136523016348631
12955060	991	select min, max, avg, where	select     column_name,     min(length(column_name)) as min,     max(length(column_name)) as max,     avg(length(column_name)) as avg from columns where column_name like '%password%' group by column_name 	0.187383937854612
12961444	1668	ms-sql sort output in descending order	select * from (  select distinct top 7 datename(mm, mydatetime) + ' '                                + cast(day(mydatetime) as varchar(2)) as thedate,                                month(mydatetime)                     as themonth,                                day(mydatetime)                       as theday,                                count(page)                           as totalcount,                                count(distinct page)                  as visitors          from   sometable          where  page like '%aec%'          group  by datename(mm, mydatetime) + ' '                    + cast(day(mydatetime) as varchar(2)),                    month(mydatetime),                    day(mydatetime)          order  by month(mydatetime) desc,                    day(mydatetime) desc) a order by themonth, theday 	0.164190057969075
12964537	15021	how to get node name in oracle sql extract() with xpath (10g)	select xmltype('<root><a><b>2</b><c>3</c><d>4</d></a></root>')        .extract('root/a/*[2]')        .getrootelement()   from dual; 	0.0297509196175142
12967086	38739	create the sql query to get a single latest value for each unit_id	select      a.*  from      mytable a     join (select                unit_id,                max(timestamp) 'timestamp'            from                mytable            group by unit_id          ) as b     on a.unit_id = b.unit_id and a.timestamp = b.timestamp 	0
12967982	13517	group by/order by two columns - get data without losing rows - mysql	select * from `number_color_style` order by `number_color_id` , `number_style_id` 	0.000313762011406088
12991383	39896	how do i create a table containing a column type of money that is by default set to zero?	select 1234::text::money; 	8.33455143141161e-05
13006091	39002	i need to combine multiple rows from a subquery into a string separated by a space	select     a.[imageid],      a.imagefile,     a.[imagetitle],     a.[imagecaption],     a.[description],     a.[active],     c.[listingid],     c.[active],     c.[levelid],     c.[title],     stuff     (         (         select ' ' + cast(tt.albumid as varchar(10))         from bd_albumgallery as tt         where tt.[imageid] = a.[imageid]         for xml path(''), type         ).value('data(.)', 'nvarchar(max)')     , 1, 1, '') as listings from bd_gallery as a     left outer join bd_listing as c on a.listingid = c.listingid where     a.listingid = @passedlistingid and     a.active = 1 and c.active = 1 and     c.levelid > 5 	0
13007671	13363	use order by in union all	select * from     (         select username, amount from employee         union all         select '' as username, sum(amount) from employee     ) x order by (case when username = '' then 1 else 0 end) asc,            cast(username as signed) asc 	0.217803221473724
13010988	13591	how to find duplicate entrys in below structured table in mysql	select count(*) as `c`, `email_address`, `phone_number`, ... from `phone_observations` group by `email_address`, `phone_number`, ... having `c`>1 	0.00644946788454557
13032551	25301	omit all the results even if one row has a different value	select var1, var2, status from mytable where not exists (select 1 from mytable where status != 'completed') 	0
13033902	22457	sql - how to return rows containing all children rows	select parent_id   from xreftable   where ref_id in ( 2, 3 )   group by parent_id   having count(distinct ref_id) = 2 	0
13051724	37940	order rows within groups in postgresql	select    routeid,    'srid=4326;linestring(' || string_agg(lon || ' ' || lat, ',' order by time asc) || ')' as the_geom from route_table  where observation_time between '2012-09-12 10:00:00' and '2012-09-12 10:15:00' group by routeid having count(lon) > 1; 	0.0121782055241823
13064378	39166	oracle, can't get details from the same column	select * from parameter where name='from' and to_date(value, 'dd/mm/yyyy') >= to_date('01/11/2012', 'dd/mm/yyyy') and to_date(value, 'dd/mm/yyyy') <= to_date('20/11/2012', 'dd/mm/yyyy') union select * from parameter where name='to' and to_date(value, 'dd/mm/yyyy') >= to_date('01/11/2012', 'dd/mm/yyyy') and to_date(value, 'dd/mm/yyyy') <= to_date('20/11/2012', 'dd/mm/yyyy') 	0.000668175473905055
13066724	7802	get sum of another row of group by'd rows	select d1.data_id,   d1.data_content,   d1.var_name,   d1.var_line,   t.total,   w.weight from data d1 inner join (   select data_content,     count(data_content) total   from data   group by data_content ) t   on d1.data_content = t.data_content inner join (   select var_line,     sum(case when var_name = 'gnd_wt' then data_content end) weight   from data   group by var_line ) w   on d1.var_line = w.var_line where d1.var_name = 'gnd.new.int' 	0
13068513	7202	sort by different columns	select * from (select * from                 categories order by                 post_count desc limit 4) as a order by name 	0.00214689305202621
13077522	32696	select rows missing from link table	select contacts_options_full.contactid, contacts_options_full.optionid, options.serviceid from (   select contactid, optionid   from (select optionid from options) o   cross join   (select distinct contactid from contactoptions) co ) contacts_options_full left join contactoptions on contacts_options_full.contactid = contactoptions.contactid and contactoptions.optionid = contacts_options_full.optionid join options on contacts_options_full.optionid = options.optionid where contactoptions.serviceid is null order by contacts_options_full.contactid, contacts_options_full.optionid 	0.000588193126630782
13078062	6557	merging records with sql, with some rules	select a.name as name,( select isnull(b.instrument, '')+ ' ' from dbo.coexample b where b.name=a.name for xml path('')) as instrument, max(cast(boolean1 as int)) as boolean1, max(cast(boolean2 as int)) as boolean2 from dbo.coexample a group by a.name 	0.0150725261357295
13088636	30435	detecting change of status in a time series	select distinct   t1.id from   table_1 t1     inner join   table_1 t2     on       t1.id = t2.id and        t1.boolean = true and        t2.boolean = false and       datediff(second, t1.timestamp, t2.timestamp) between 0 and 1 	0.00476884823108361
13098008	8151	have to get data from visit_table filter with only date no time	select convert(varchar(10), visit_date, 120) as [date],id from patient_visit 	0
13106173	32460	finding similar rows in mysql	select distinct case when locate('[', title)-1 = -1                       then trim(title)                       else trim(left(title, locate('[', title)-1))                 end title from table1 	0.00582648382028717
13119350	39347	using tsql to create a contigious time line set	select productid, warehouseid, cost, min(saledate), max(saledate) from (           select *,         row_number() over (order by saledate)-         row_number() over (partition by cost order by saledate) grp     from @orderdata ) v group by productid, warehouseid, grp, cost order by warehouseid, min(saledate) 	0.0522384539678623
13150719	36886	how could we design database for table job subjob and contract?	select * from subjobs where subjobs.parent_job = {jobid}; 	0.71750350205285
13153340	21030	mysql query - select all posts and count comments for each one	select p.*, x.* from blog_posts p left join  (     select post_id, count(*) as cc     from blog_comments     group by post_id ) x  on x.post_id = p.id; 	0
13154807	40133	query required for given output	select field1       , f2       , f3       , 'flow'||trim(to_char(rnk)) from       (select field1       , f2       , f3       , sum(case when f3 = 1 then 1 else 0 end)      over (order by field1, f3 range between unbounded preceding and current row) rnk     from your_table ) 	0.194015434806967
13167845	14035	sql, group by, merge strings	select name, sum(count1), sum(count2), address from mytable group by name, address; 	0.0839529357364248
13173258	505	how do i build a query that crosses multiple tables?	select  c.*,         p.* from    customer c inner join         orders o    on  c.cust_id = o.cust_id inner join         order_line ol   on  o.order_id = ol.order_number inner join         part p on   ol.part_number = p.part_number 	0.328520335523411
13187546	34144	show me the index on the table in oracle	select index_name   from all_ind_columns  where table_name = 'the_table'    and column_name = 'the_column'    and index_owner = 'the_owner'; 	0.086408553264145
13195025	21207	return a substring from a field in sql	select id, substring(content, patindex('%ctid%', content) + 5, patindex('%[^0-9]%', substring(content, patindex('%ctid%', content) + 5, 12)) - 1) as ctid        from articles where content like '%ctid%' 	0.00436582254605419
13203513	23285	cte linking on different id fields	select  internalidentifier, npi, lastname, firstname, specialty, dob, degree, department, [state license number], [upin number], [physician status],      [doctor_number], address,city, state, zip, phone, fax from cte1 right outer join cteview on cteview.[doctor_number] = cte1.[doctor number] 	0.000406531012647517
13229095	239	mysql order by custom	select.. from... where... order by field(id,5,8,6,7) 	0.622135307420526
13248669	28010	sqoop free form query split by alias	select xyz from (     select       convert(varchar,table1.field1) + '_' + table2.field1 as 'xyz'      from         table1     inner join   table2      on           table1.field3 = table2.field4 ) as sub where $conditions 	0.20125598113481
13256993	14999	merging 2 android sqlite queries in a train schedule app	select fromsch.trainid,        fromst.name,        fromschst.departure,        tost.name,        toschst.arrival from    stations          fromst    join schedule_stations fromschst on fromst._id = fromschst.stationid    join schedule          fromsch   on fromschst._id = fromsch.schedulestationid    join schedule          tosch     on fromsch.trainid = tosch.trainid                                    and fromsch.day = tosch.day    join schedule_stations toschst   on tosch.schedulestationid = toschst._id    join stations          tost      on toschst.stationid = tost._id where  fromst._id = ?    and tost._id = ? 	0.227977686046282
13259980	9909	how do i get a single result, from two tables, where the 2nd table contains an updated version of a record from the 1st?	select ca.databaseid,         coalesce(mca.id, ca.id) as id,        coalesce(mca.name, ca.name) as name,        coalesce(mca.street, ca.street) as street,        coalesce(mca.city, ca.city) as city,        coalesce(mca.zip, ca.zip) as zip,        coalesce(mca.maintdate, ca.maintdate) as maintdate,     from companyaddresses ca        left join mycompanyaddresses mca            on ca.code = mca.code; 	0
13273016	11975	mysql select if match one value only	select userid from tablename a where file = 2 group by userid having count(*) =  (   select count(*)   from tablename b   where a.userid = b.userid  ) 	0.000199303494906374
13276128	9610	find duplicate rows in mysql simplified example	select count(*) as cnt, group_concat(rel_id) as ids from rels group by host, host_type, rep, rep_type having cnt > 1 	0.0188567617819022
13276490	38851	mysql find matching key with mismatched value	select lp.pid, group_concat(lp.lpid) as lpids, group_concat(lp.pname) as names from lp inner join (   select pid, count(distinct pname) as names   from lp   group by pid   having count(pid) > 1 and names > 1 ) dup on lp.pid = dup.pid group by lp.pid 	0.00298008351223604
13278315	15972	sql statement that subs 0 for no results	select u.firstname + ' ' + u.lastname as name, count(f.id) as 'open requests' from users u inner join roles r     on u.roleid = r.id  left join ( select * from frrequests              where status in ('submitted','delayed')) f     on u.id = f.userid where r.name = n'field rep'  group by u.firstname, u.lastname 	0.233420747364321
13279685	33658	joining sql tables on the column that has a value	select c.collectionid, isnull(d.movieid, s.movieid) movieid from collection c left join director d on d.director=c.directorid left join studio s on s.studio=c.studioid 	6.24790336397983e-05
13291770	19824	mysql max() without being able to group	select  foo.id,         foo.val,         (select max(bar.val) from bar where bar.val < foo.val) as barval from foo 	0.319410460093231
13298960	25728	sql query to aggregate on date	select i.date,        max(case when p.type = 1 then p.name end) as type1,        max(case when p.type = 2 then p.name end) as type2,        max(case when p.type = 3 then p.name end) as type3,        max(case when p.type = 4 then p.name end) as type4 from infos i left outer join      provider p      on i.provider_id = p.id group by i.date 	0.315468210474406
13305050	37994	discriminate sybase ase from microsoft sql server	select @@version 	0.597552451937917
13328429	29145	can i select the row of a table and retrieve the name of the table that i am selecting?	select *, 'page' as table_name from page; 	0
13335080	3391	if not exists in another table, set to null	select rec.id, title.name from records rec left join titles title on title.record_id = rec.id and title.language='de'; select rec.id, title.name from records rec left join titles title on title.record_id = rec.id and title.language='en'; id  name 1   achtung 2   (null) id  name 1   warning 2   ambulance 	0.0151308013903057
13353154	25499	concat a subquery result and fixed strings	select x.vname, x.id, concat(x.vname, '..' ,(select t.id from t where t.x_id=x.id limit 1), '..', 'some_text') from xtable 	0.187318911321079
13359092	13763	inserting a new column into sql	select name,    description,    project,   costcategoryid,    right(costcategoryid,14) as costbreak  from dbo.graud_projectsbycostcategory 	0.00486401651400906
13370928	14775	extraction from two tables	select ifnull(b.number>0,0) output        from products a   left join (               select count(*) number,                      product_name                 from purchases                where userid = '001abc'             group by product_name            ) b on a.product_name = b.product_name   order by a.product_id 	0.00231331386861395
13371144	11729	grouping the ip addresses returns 15 instead of 3	select count(distinct info_ip) from photos_watched where idp = 19; 	0.00467181922144532
13373352	22146	how to merge rows with oracle sql	select  "t#",  max(decode(leg,1,origin)) origin,  max(decode(leg,1,destination)) destination, max(decode(leg,2,destination)) destination2 from tripleg group by "t#" 	0.0177627346863941
13376223	14529	how to convert string to integer - weird format	select cast((columnname * 100) as integer) newvalue from tablename; 	0.201947009289801
13380296	21828	how to get the fields and it's count (occurances) in a table in sqlite(android)?	select count(*),name from candidates where name ='james' 	0
13385042	25150	search mysql column for duplicates and add suffix to variable in while loop	select distinct news.*, count(older.newsid) as older from tblnews news left join tblnews older on older.newstitle = news.newstitle and older.newsid < news.newsid where year(news.newsdate) >= $startyear and year(news.newsdate) <= $endyear and news.newspageid = 13 group by news.newsid order by news.newsdate desc; 	0.3243182632253
13385755	39233	display unique data from two tables	select id, subid from tbla union  select id, subid from tblb 	0
13385990	4048	retrieving rows based on a certain criteria regarding a many-to-many mapping in hibernate	select colour from colour colour  where colour.id not in (     select colour2.id from product product     inner join product.colours colour2     where product.id = :productid) 	0.000102632706897834
13388139	23064	show subreport multiple times based on multi-value parameter	select shopid where shopid in (@shopid) 	0.000350680344589194
13388210	14838	return unique row for every duplicate in mysql table	select a.id id1, b.id id2, a.model model1, b.model model2 from products a join products b   on a.alt_model=b.alt_model             and a.id < b.id                        order by id1,id2; 	0
13396447	16680	php/mysql query if not in second table	select u.*,c.userid  from `users` u left join `catuser` c on u.id = c.userid  where u.id = '1' and c.userid <> '197' and c.userid is null 	0.0253473697991312
13410566	4643	sql joins with ambiguous columns	select     c.course_name,     c.course_number,     p.course_name as prereq_course_name,     p.prereq from rearp.course as c, rearp.prereq as p where c.course_number = p.course_number 	0.765724718558586
13416153	8540	order by field in mysql	select a.col as type,coalesce (`count`,0) as `count` from  (select 'a' as col union all select 'b' as col union all select 'c' as col union all select 'd' as col )a left join table1 t on a.col=t.type order by field(a.col,'a','b','c','d') ; 	0.111220903272474
13417907	36074	select distinct from 2 columns but only 1 is duplicate	select     war.subscriber_msisdn   , war.created_datetime from   wiz_application_response war   left join wiz_application_item  wai     on war.application_item_id = wai.id     and wai.application_id = 155 where   war.created_datetime between '2012-10-07 00:00' and '2012-11-15 00:00:54' 	0
13427318	15238	mysql query for a matrix	select f1, count(f1), f3 from evaluation group by f3, f1 	0.453808677037552
13435371	31613	long string stored in varchar mysql outputs as one line	select * from example_table\g 	0.277790469833917
13449609	21472	select the previous x rows	select * from image order by image_id desc limit (x-10), 10 	0.000163656826410143
13451654	16973	select multiple rows from a table	select identifier, name  from content  inner join rawidentifiers on content.identifier = rawidentifiers.identifier 	0.000399794859919376
13459115	23355	aggregate columns into yearly/monthly/weekly	select  c.interval,         main.subscriberid,         stuff((             select '|' +              (cast(sub.contentid as nvarchar(10)) + ',' +               cast(count(contentid) as nvarchar(100)))              from tablea sub             where             sub.subscriberid = main.subscriberid             group by contentid             for xml path('')             ), 1, 1, '' )         as [result]         from  tablea main         cross join         (    select 356 as days, 'year' as interval              union all               select 30 days, 'month' as interval              union all               select 7 days, 'week' as interval         ) c         where          dateadd(day, datediff(day, 0, senddate), 0) >=          dateadd(dd, datediff(dd, 0, getdate()), 0) - c.days 	0.0334782144207345
13461262	18842	is there a quick way to re-format all values in a coldfusion query column?	select varchar_format(timestamp_format(cast(20121119 as char(8)), 'yyyymmdd'), 'mm/dd/yyyy') from sysibm.sysdummy1 	0.353761503225055
13467683	14967	select sum of column from a table where column has specific text	select sum(price) from `service` where `servicedby` like '%trucks%' 	0
13471751	12833	postgresql - divide query result into quintiles	select t.id, ntile(5) over (order by t.id) from t 	0.0746553117922594
13507015	22050	select distinct from multiple row and do not return if containing row with undesired value	select distinct id_number from   <table> where  id_number not in(select id_number from <table> where grade <> 'passed') 	0
13507441	13077	unable to get xml records into temp table via openxml	select t.n.value('@name', 'varchar(100)')name,   t.n.value('value[1]', 'varchar(100)')value  from @xml.nodes('/newdataset/data') as t(n) 	0.00127826170113931
13511664	30963	mysql: select and count in same query	select city.id, city.name, city.slug, count(club.id) as club_count from city inner join club on city.id = club.city_id where club.published = 1 group by city.id, city.name, city.slug having club_count > 0 	0.028848841638957
13514173	37937	mysql equivalent of ms-access function first() last()	select id, min(image) from tbl group by id 	0.0670545280561117
13539751	15748	avg count query	select h.country, count(w.ic) / count(distinct h.hid) as [average] from hospital as h     left outer join work as w on w.hid = h.hid group by h.country 	0.437612224685195
13542901	10223	how to have a single result with a join?	select projects.id,        projects.title,        min(comments.message) as comment_message    from "projects"  right  outer   join comments     on comments.project_id = projects.id  group     by projects.id ; 	0.0165065497715509
13544506	35481	add a filter to a large mysql query	select ... where tbl_product.active='y' and (tbl_dealinterest.active <> 'n' or tbl_dealinterest.active is null) ... 	0.125170326684357
13549828	37423	mysql on select statement from 2 fields and distinct value	select distinct leg.destination city from trktripleg leg where leg.t# in (select t# from trktrip trip where l#='10001' or l#='10002') union select distinct leg.departure city from trktripleg leg where leg.t# in (select t# from trktrip trip where l#='10001' or l#='10002') 	0.000292053875684738
13553392	37417	mysql sum each distinct client_id	select client_id, count(*) as topclient from projects group by client_id order by topclient desc limit 10; 	0.00108250646274886
13553450	23760	sql: and / or matches with a many-to-many join	select * from photos p where 1=1 and exists ( select * from photos_term pt     where pt.photo_id = p.id and term_id in (1,2)     ) and exists ( select * from photos_term pt     where pt.photo_id = p.id and term_id in (3,4,5)     ) and exists ( select * from photos_term pt     where pt.photo_id = p.id and term_id in (6)     )     ; 	0.64629479088443
13555843	2887	how to find the average of a count result in mysql?	select avg(number_of_cds_released) from (select labelname as record_labels, count(title) as number_of_cds_released from cd join recordlabel on labelname = released_by group by labelname) nested; 	0
13562376	21390	mysql select from multiple tables based on common relationships	select sg.group_name, a.dept_name  from sys_groups sg  inner join (select gda.group_id, group_concat(sd.dept_name separator '|') dept_name             from group_dept_access gda              inner join sys_department sd on gda.dept_id = sd.dept_id              group by gda.group_id) as a on sg.group_id = a.group_id 	0
13590606	31962	returning the results only when the user has permissions	select      (select          1      from          permissions      where          permissions.user_id=<user id> and permissions.book_id=<book id>)     ) as permission,     * from     books where     books.id=<book id> 	0.00183180054250509
13608272	27780	how to put the first date of this year in a where clause. mysql	select ... from   ... where date_sub(curdate(), interval 1 year) <= date and       year(your_datecolumn) = year(curdate()) 	0.000642981868536923
13632476	6118	get the max number of rows by id	select count(*)  from anonym where id = (select max(id) from anonym) 	0
13634125	29775	php mysql grouping result	select  stud.section, stud.name, group_concat(subj.subject, '')  from table_students stud  join table_subjects subj  on stud.student_id = subj.student_id  group by stud.name 	0.200813492942166
13647344	8985	mysql query for getting joomla users and their profile fields	select     #__users.*,     max(case when profile_key = "example.firstname" then profile_value end) as firstname,     max(case when profile_key = "example.lastname" then profile_value end) as lastname,     max(case when profile_key = "example.company" then profile_value end) as company from #__users left join #__user_profiles on #__users.id = #__user_profiles.user_id group by #__users.id 	0.00167734996816435
13647731	36446	obtain the sum from a column by id from an un-normalized table?	select   doctor_id, sum(medicine) medicine, sum(radiology) radiology from     (   select   max(doctor_id) doctor_id,            sum(if(pm='f', cost, null)) medicine,            sum(if(pm='r', cost, null)) radiology   from     my_table   group by trans_no ) t group by doctor_id 	0
13651516	15048	how to combine two tables into one table using the data from one table as the columns?	select   id,   max(case when phonetype=1 then phonenumber end) as home_phone,   max(case when phonetype=2 then phonenumber end) as work_phone,   max(case when phonetype=3 then phonenumber end) as mobile_phone from person group by id 	0
13657859	39917	select query using in() and without any sorting	select *  from product  where productid in(25,36,40,1,50)  order by find_in_set(productid, '25,36,40,1,50'); 	0.479291699697763
13663743	2834	how do i perform a between query on a db that all ready has multiple joins?	select        id    from        wp_posts          inner join wp_postmeta m1             on wp_posts.id = m1.post_id            and m1.meta_key = 'a_property_type'            and m1.meta_value = '$meta_type'          inner join wp_postmeta m2            on wp_posts.id = m2.post_id           and m2.meta_key = 'a_bedrooms_min'            and m2.meta_value <= '$meta_bedrooms'          inner join wp_postmeta m3            on wp_posts.id = m3.post_id           and m3.meta_key = 'a_bedrooms_max'            and m3.meta_value >= '$meta_bedrooms'    where           wp_posts.post_type = 'alerts'       and wp_posts.post_status = 'publish'    group by        wp_posts.id    order by        wp_posts.post_date desc; 	0.00439067117545786
13665927	25502	sorting mysql results by multiple columns	select * from gym where city = "queens" and state = "ny" order by   isnull(priority), priority,   isnull(photo),   isnull(member_includes), member_includes,   isnull(reviews), reviews desc limit 150 	0.0274311680774538
13669645	28269	displaying displayname on another table rather than the foreign key from another table when click a link php mysql	select tvshows.user_id, users.displayname from tvshows, users where (tvshows.user_id = users.user_id) and (tvshow_id = '$tvshow_id') 	0
13673395	30452	mysql5.1 query with join and count	select teams.`team_name`, count(matches.`played_team`)  from teams  join matches on teams.`team_number` = matches.`played_team` where `matches.date` > '2011-01-01'  group by teams.`team_name` 	0.635714500903096
13673956	4750	retrieving records with multiple keys. openjpa	select ...   where colx = val1 and coly = val2 and colz = val3 	0.00132946819658415
13714407	12673	count results in column connected with distinct id sql	select p.name,     sum(case when p.player_id = g.p1_id and g.p1_score>g.p2_score          or p.player_id = g.p2_id and g.p1_score<g.p2_score then 1 else 0 end) games_won,     sum(case when p.player_id = g.p1_id and g.p1_score<g.p2_score          or p.player_id = g.p2_id and g.p1_score>g.p2_score then 1 else 0 end) games_lost,     sum(case when g.p1_score=g.p2_score then 1 else 0 end) games_tied from player p inner join game g on p.player_id in (g.p1_id, g.p2_id) group by p.name 	0.00295765399422525
13717682	40072	how to select one unique value in mysql for the first row then show nothing for that value, but show all the records?	select cfgn from (    select concat('\t',                  config_option_name,                  '=',format(price, 2) ) as cfgn,                   config_id,                  t2.id,                  config_option_name,                  price     from table2 t2    join table1 t1 on (t2.config_id=t1.id)    union all    select concat(cast(id as char),                  '. ',config_name) as cfgn,            id config_id,           null id,           config_name,            null price     from table1  ) t3 order by config_id,id 	0
13719523	10957	calculate time difference amount in minutes with mysql or php?	select user_id from t  where login_date= curdate()        and login_time>timestampadd(minute,-3,curtime())       and status = 'f' group by user_id  having count(*)>3 	0.00015717356547181
13730571	25973	postgres - how to typecast sum(bigint) to bigint?	select sum(big_col)::bigint as total  from big_table 	0.21587612825312
13754371	25607	sql query: does one to many relationship contain elements x	select s.studyid,           max(case when language='english' then 1 else 0 end) isinenglish,           max(case when language in ('english','french') then 1 else 0 end) isineuropeanlanguage      from study s left join languages l on s.studyid = l.studyid  group by s.studyid 	0.00266687449489688
13758675	8291	complex select query for mysql combining two column with where clause	select faculty_id, fname, availibility as qualification from faculty a, faculty_details b where a.fac_det_id = b.fac_det_id and course_id = $your_course_id; 	0.762409222918446
13764589	7360	sql rounding to 7 places, even though its set as decimal(18,4))	select (cast(datediff(minute,'1900-01-01 07:03:00.000' ,'1900-01-01 10:35:00.000')/60.0 as decimal(18,4))) 	0.0155262111793208
13805619	10387	how do i count the most common entry in a table using sql?	select member_no, totalentries from (select member_no, count(*) totalentries, rownum as seqnum       from yourtable       group by member_no        order by 2 desc      ) t where seqnum = 1 	0
13807905	10766	mysql statement search all tables for one specific column?	select * from information_schema.columns  where lower(column_name) = 'discount' or lower(column_name) = 'discounts'; 	0.00049570598489536
13817991	2325	checking two sql conditions and display it in a same column	select p.[port name], cr.name as country, c.name, c.address, c.city from [sales invoice header] sih inner join port p on p.code = sih.port inner join country_region cr on cr.code = sih.[country of final destination] inner join customer c.no_ = sih.[sell-to customer no_])  where no_ = 'pexp1213-523' and sih.[ship_to code] = '' union all select p.[port name], cr.name as country, sih.name, sih.address,sih.city from [sales invoice header] sih inner join port p on p.code = sih.port inner join country_region cr on cr.code = sih.[country of final destination] where no_ = 'pexp1213-524' and sih.[ship_to code] <> '' 	0.000147606648807722
13820066	39730	mysql join with grouping and ordering	select c.*, (select preview   from images img   where img.cid = c.cid   order by img.id desc  limit 1) as preview from categories c 	0.657760182509558
13820261	26760	sql view conditions	select          p.pr_id         ,p.plotarea         ,p.ownershiptitle         ,p.price         ,p.notarycosts         ,p.agentfee         ,p.ctrno         ,isnull(p.price,0)-isnull(a.price,0) as diferente         ,isnull(p.price,0)+isnull(p.notarycosts,0)+isnull(p.agentfee,0) as totalcosts from nbprocuri p       left join nbachizitii a       on p.plotarea = a.plotarea and p.ctrno=a.ctrno where a.ctrno is null and a.plotarea is null 	0.498276858654491
13826204	34500	fetch related rows from tags (slow query)	select  ta.tag, ta.article_id, ar.article_title from  tags ta  inner join tags tb on ta.tag = tb.tag and tb.article_id <> ta.article_id inner join articles ar use index (category_id) on tb.article_id = ar.article_id where ta.article_id = $currentarticleid  and ar.category_id = $currentcategoryid  and ar.status = 1 	0.00142391705694249
13847475	29557	misunderstanding during date comparison sql	select distinct e.empid, e.firstname     from hr.employees e      where  e.empid in (select  empid     from sales.orders as s     where  orderdate  >= '20080212'            and            orderdate < '20080213') 	0.11824424511042
13857826	25544	counting the number of occurrences of a certain month in sql	select  datepart(month, datecolumn) as month ,       count(*) as numberofactions from    actions group by         datepart(month, datecolumn) 	0
13867116	11434	sqlite select with join to result all relationship data	select f.*, de.title as energydrinktitle, de.[picture] as energypicture, di.title as inspdrinktitle, dr.title as relaxdrinktitle  from (select m.*, e.descriptiontitle, i.[descriptiontitle], r.descriptiontitle,  e.[drinkid] as energydrink, i.drinkid as inspdrink, r.[drinkid] as relaxdrink from  [member] m left join [energy] e     on m.[_id] = e.[memberid] left join [inspiration] i     on m.[_id] = i.[memberid] left join [relax] r     on m.[_id] = r.[memberid] ) as f join drink de on f.energydrink = de._id join drink di on f.inspdrink = di._id join drink dr on f.relaxdrink = dr._id 	0.0148296910388657
13883595	7976	how do i calculate the importance/weight of input based on users reputation?	select 1 - log10(select count (*) from user   where (sum(user.points) / count(user.*)) < user.points)    / select (count (*) from user)) 	0
13890035	29057	sql: selecting from three tables	select a.field from a join b on a.key = b.key join c on b.key2 = c.key2 where c.field = 'some_data'; 	0.00238544528497169
13897024	11611	sql order by on multiple column	select * from(     select          vendorname,          incidentid,          incidentstatus,          incidentdate,          max(incidentdate) over (partition by vendorname) maxdate     from yourtable ) t order by t.maxdate desc, t.vendorname asc, t.incidentdate desc 	0.057647578440504
13901247	38715	getting unique group by values over 4 different columns	select      c.id, c.name from     specials     inner join restaurant as rest on specials.restaurantid=rest.id     inner join cuisine as c on c.id in (rest.cuisine1, rest.cuisine2, rest.cuisine3, rest.cuisine4) where     dateend >= curdate() and     (specials.state='vic' or specials.state = 'all')  and      specials.status = 1  and      rest.status = 1 group by     c.id; 	4.83996306064586e-05
13907507	6996	pick a random value from a set t-sql	select ac1.id, r.color from (select top (100) row_number() over (order by newid()) as id, row_number() over (order by newid()) as dummy from sys.all_columns order by id ) ac1 cross apply (select top 1 color from ( values (0,'red'),(1,'green'),(2,'yellow') ) colors(id,color)  where id = dummy % 3 ) r 	0.000211905494239004
13909312	9446	mysql query for order by	select   t.* from atable t inner join (   select     block,     max(releasedate) as highestdate   from atable   group by block ) s on s.block = t.block order by   s.highestdate,   t.settype,   t.block,   t.releasedate ; 	0.52802035102457
13911325	14857	sql one result per match	select * from (   select      p.product_id,      p.price,      row_number() over (partition by product_id order by p.creation_date desc) rn,     p.creation_date   from price p   inner join product pr     on p.product_id = pr.product_id      and p.filter_id = 3      and (p.store_id in (1,2,3,4) or p.price_type = 'a')  ) where rn = 1 	0.00110096419312735
13911770	14643	how to find valid date on tables	select * from table where isdate(column)=1 	0.00350919458851146
13913948	7034	upcoming event script	select * from eventtable where date > curdate() order by date limit 0, 1; 	0.136701585790752
13932427	19425	coalesce the other way around	select   id,          max(if(stage = 'a', num, null)) as `a`          max(if(stage = 'b', num, null)) as `b`          max(if(stage = 'c', num, null)) as `c` from     foo group by id 	0.709062253266611
13962862	37660	how can i count the average number closest to 100?	select user_id, sum( abs(100-score) ) as cumulative_error,   date(playtime) as playdate  from playtable group by user_id, date(playtime)  order by playdate desc, user_id 	5.67229851060676e-05
13965028	27014	select trouble with difftime	select hour(timediff('2012-12-19 22:00:00','2012-12-10 19:00:00')); 	0.76526896860465
13967754	29804	sql server 2008 query to put null for non existing values	select      name,      (select contact       from contacts c       where c.type = 'p' and c.personid = p.personid)      as contact from      persons p 	0.0629326980998429
13968027	21844	sql merge two tables in which the common fields are not complete	select  coalesce(t1.c1, t2.c1) ,       t1.c2 ,       t2.c2 from    table_1 t1 full outer join         table2 t2 on      t1.c1 = t2.c1 	7.9519069859245e-05
13968169	20890	how i get record from two tables?	select  emp.*,usr.*   from employee emp inner join user usr  on emp.empid = usr.empid 	0
13975214	27289	sql - trying to iterate through partitions to find duplicates	select   ai.telephone1 as [main phone #]         ,ai.new_id as [id]         ,ai.name as [account name]         ,ai.emailaddress1 as [email address]         ,ai.contactname as [primary contact] from accountsinfo ai inner join  (         select telephone1,new_id         from mydatabase.dbo.accountsinfo ai         where telephone1 != 'null'             and telephone1 != '         group by telephone1, new_id         having count(*) > 1 ) t on ai.telephone1 = t.telephone1 and ai.new_id = t.new_id order by ai.telephone1 	0.0499648294354482
13976960	35574	mysql - multiply columns by alias	select s.pid as 'id',         concat_ws(', ', p.lastname, p.firstname) as 'name',         concat(s.date, ' ', s.time) as serviced,         p.institution as facility,         s.description as 'description title',         ((select count(*)            from series se           where se.studyid = s.id)            *         (select count(*)            from image i           where i.seriesid = se.id)            ),         as 'number of images'    from product p,            series se         join            study s         on s.pid = p.id  group by s.id  order by serviced desc 	0.0831204646112152
13986801	19018	timeslot availability multiple days mysql	select starttime, endtime from timeslots where   not exists (                         select room, startdatetime, enddatetime from scheduler     where room = 'room1'     and date(startdatetime) =  '2012-12-20'     and          (startdatetime <= concat('2012-12-20', ' ' ,endtime) and         enddatetime >= concat('2012-12-20', ' ' ,starttime))     ) 	0.0328969988080753
13990797	16166	return all columns from table 1, and one column from table 2	select al.*, ph.column_name from album as al inner join photo as ph on album.album_id=photo.album_id  group by album.album_id 	0
14009925	4683	show percent of count and count both booleans	select   studentid,   name,    sum(present) as present,   sum(present = 0) as absent from your_table group by studentid, name having present < .75 * (present+absent) 	0.000636825969466442
14020919	31424	find difference between timestamps in seconds in postgresql	select extract(epoch from (timestamp_b - timestamp_a)) from tablea 	8.6588552084315e-05
14037334	7666	using decode to check for negative and positive values	select case   when money_return < 0 then abs(money_return)  when money_return > 0 then money_return*10  else money_return end money_return from cash_t; 	0.0134544729587423
14042594	25771	all column data in one column separated by special character say -	select id, concat_ws('-', col1, col2, col3, col4, col5, col6, col7, col8, col9) from your_table 	9.27743313657251e-05
14045057	28129	mysql: selecting persons who have a certain amount of relational rows	select distinct id from person  where id in     (select person_id       from event_registration       group by person_id having count(*) <= 10) 	0
14059053	14210	query a mysql database for the number of entries with a date later then the current date	select count(*) as 'count' from my_table where my_datetime_column > now() 	0
14074552	24168	need to pull data from mysql by unique userid, max rounds, then sort by another value	select userid, rounds, maxreps from (select userid, l.rounds, max(l.reps) as maxreps       from leaderboard l       where l.exerciseid = 8        group by l.userid, l.rounds      ) ur where exists (select 1 from leaderboard lb where ur.userid = lb.userid and lb.exerciseid = 8 group by lb.userid having max(rounds) = ur.rounds)) order by rounds desc, maxreps desc 	0
14085534	26624	sort items in mysql with dots	select * from table order by cast(id as decimal) asc 	0.0392593952264515
14090352	25375	sql query to select one row from each group with preference	select distinct   t1.y,   coalesce(a2.x, a1.x) 'x' from tablename t1 left join (     select y, min(x) x     from tablename     group by y ) a1 on t1.y = a1.y left join (     select y, min(x) x     from tablename     where x = 'a'     group by y ) a2 on t1.y = a2.y; 	0
14097043	33557	count() on where clause from a different table	select sql_calc_found_rows p.*, count(l.like_id)        case            when p.specials_new_products_price > 0.0000                 and (p.expires_date > now()                      or p.expires_date is null                      or p.expires_date ='0000-00-00 00:00:00')                 and p.status != 0 then p.specials_new_products_price            else p.products_price        end price from ".table_global_products." p inner join ".table_stores." s on s.blog_id = p.blog_id inner join ".table_global_likes." l on l.blog_id = p.blog_id and l.products_id = p.products_id where match (p.products_name,              p.products_description) against ('*".$search_key."*')   and p.display_product = '1'   and p.products_status = '1' having price <= ".$priceto_key."   and price >= ".$pricefrom_key." group by p.products_id having count(l.like_id)>0 order by p.products_date_added desc, p.products_name 	0.00413271289031874
14104628	26542	sql to pick n rows from each value of where clause	select a.* from  (  select employeename ,   row_number() over(partition by state order by employeename) as rn  from employee where state in ('ny','ca','tx')  )a where rn <=10; 	0
14107013	4579	compare 2 tables in sql	select * from a1 where not exists (select * from a2 where a2.id = a1.id) 	0.00682777195551557
14111294	35860	mysql how to rank objects by similarity of multiple property rows	select  other.objectid ,       avg(abs(target.score - other.score)) as delta from    scores target join    scores other on      other.metricid = target.metricid         and other.objectid <> target.objectid where   target.objectid = 1 group by         other.objectid order by         delta 	0.000844929760627274
14114655	13627	postgresql, comparing text as datetime	select ... from ... where     to_timestamp(mydate || mytime, 'dd.mm.yyyyhh24:mi:ss') between         '2012-01-20 10:23:12'         and         '2012-01-20 11:47:03' 	0.12001476743363
14119277	11979	subtract two dates in sql and get days of the result	select i.fee from item i where  datediff(day, getdate(), i.datecreated) < 365 	0
14146779	6924	multiple rows in query from one row	select [date], other_column from dbo.mytable cross apply dbo.getnums([count]); 	9.71362357322977e-05
14163188	25701	dynamic where clause with set number of columns	select * from table where isnull(@param1,field1)=field1 and isnull(@param2,field2)=field2 and isnull(@param3,field3)=field3 and isnull(@param4,field4)=field4 and isnull(@param5,field5)=field5 	0.0335043146500264
14178207	22316	sql query with current day comparison	select due_day     from deals     where (due_day - dayofmonth( now( ) ) ) <=14 	0.00413075492488575
14190798	11809	how to select a column name with space between in mysql on liunx/ubuntu	select `business name` from annoying_table 	0.00242098948034342
14191021	3750	mysql: count the distinct rows per day	select  date(timestamp) date, count(distinct ipnum) totalcount from    tablename group   by  date(timestamp) 	0
14194363	5752	architecture : in sql what is the best method to query a filtered data set?	select from     table t where  ( @p_param1 is null or t.column1 = @p_param1 ) and ( @p_param2 is null or t.column2 = @p_param2 ) and ( @p_param3 is null or t.column3 = @p_param3 ) 	0.604454228400299
14198954	178	how to join these 2 mysql queries?	select t1.date_1, t1.number_1, t2.number_2 from  (select month(date_1) as date_1,         sum(number_1) as number_1    from table_1    where date_1 between '2012-01-01' and '2013-01-01'    group by month(date_1))t1 inner join (select count(distinct number_2) as number_2,         month(date_2) as date_2    from table_2    where date_2 between '2012-01-01' and '2013-01-01'    group by month(date_2)    order by month(date_2) desc)t2 on t1.date_1 = t2.date_2; 	0.206572840592764
14203188	19760	sql query showing 4x records	select c.first_name, c.last_name,      p.common_name, p.flower_colour, p.flowering_season,      s.first_name, s.last_name from customers c inner join orders o     on c.customerid = o.customer_id  inner join  plants p     on o.plant_id = p.plant_id inner join staff s     on o.order_id = s.order_id where o.order_date between  '2011/01/01' and  '2013/03/01' 	0.081586351370596
14234161	19646	select one column as multiple column on other table	select md.doc_no, md.doc_date, md.doc_type,         mp1.product_details item_details1, md.item_qty1, md.item_price1,         mp2.product_details item_details2, md.item_qty2, md.item_price2  from master_document md  inner join master_product_table mp1 on md.item_code1 = mp1.id  inner join master_product_table mp2 on md.item_code2 = mp2.id ; 	0
14243181	27945	select query with limit from database column on mysql	select user.*, messages.* from user inner join messages      on user.id=messages.user_id where (select count(*) from messages m        where m.user_id=user.id        and m.id<messages.id)<user.credit 	0.0143922186073277
14243386	4592	for each row from select insert multiple rows into one table	select    identity(int, 200, 1) idtable_3,    t1.idtable_1,    t2.idtable_2,    case t2.column when 'x' then t1.x                   when 'y' then t1.y                   when 'z' then t1.z end value into table_3 from table_1 t1   cross join table_2 t2 	0
14243748	12805	mysql - select based on multiple row conditions	select id from yourtable where val in (10, 30) group by id having count(distinct val) =2 	0.000444982035186983
14249236	39255	sql sum within range	select date, sum(daycnt) over (order by date) from (select date, count(*) as daycnt       from t       where date between day_start and day_end       group by t      ) t 	0.0208026515922497
14252059	7499	getting multiple columns for duplicate records	select    i.*,    d.duplicatecount from    iqr1 i    inner join (       select          itemcode,          duplicatecount = count(*)       from iqr1       where whscode = 01       group by itemcode          having count(*) > 1    ) d on i.itemcode = d.itemcode order by duplicatecount desc 	0.000148224182338159
14281019	18012	3 field mysql query	select case when device1 = '' or device1 is null             then 'you currently have no devices. click here to add one'             when device2 = '' or device2 is null             then device1             when device3 = '' or device3 is null             then concat(device1,' + ',device2)             else concat(device1,' + ',device2,' + ',device3)        end as output      , device1      , device2      , device3   from mytable 	0.106155117430697
14283591	21522	how to return the items in mysql greater than 6 months?	select id from your_table where your_timestamp_column <= (now() - interval 6 month); 	0
14283950	27533	sql ordering by count	select tags.pg, count(tag_refs.t_id) as tag_count from tags inner join tag_refs on tags.t_id = tag_refs.t_id group by tag.pg order by tag_count desc 	0.321815779828394
14290211	25453	set package variable to a value from database	select ? = max(some_column) from some_table 	0.00451144872763252
14301002	35886	sql list the representative that handles the most customers	select top 1 with ties rep_lname, count(cust_num) from customer inner join salesrep    on customer.rep_num = salesrep.rep_num  group by rep_lname order by count(cust_num) desc 	0.0001901174705267
14319856	24996	how do i group the results by month?	select year, month, sum(total) as total from (select year(date_added) as year, monthname(date_added) as  month, count(*) as total  from news  group by month   union all   select year(date_added) as year, monthname(date_added) as month , count(*) as total  from equipment  group by month) x group by year, month 	0.00417876401836
14328093	7964	select a column from two tables and put them into one	select table1.row as jobnumber from table1 union select table2.row as jobnumber from table2 	0
14339627	37591	choose row when grouping sql	select t1.id, t1.field_1, t2.idsum from table t1 inner join (   select field_2, max(id) id, sum(id) idsum   from  table   group by field_2 ) t2  on t1.id = t2.id      and t1.field_2 = t2.field_2; 	0.0368244287093194
14339788	26409	select a row from two tables depend on primary key(mysql)?	select  a.*, b.* from    users a         inner join album b             on a.user_id = b.user_id         inner join         (             select user_id, max(photo_id) max_rec             from album             group by    user_id         ) c on b.user_id = c.user_id and                 b.photo_id = c.max_rec 	4.61491320047873e-05
14340143	1547	join over three tables	select i.*, mainp.uri mainuri, mp.memberuri, mp.linkuri access from items i left outer join principals mainp    on mainp.uri = i.principaluri left outer join    (select memberp.uri memberuri, linkp.uri linkuri      from principals memberp       inner join members m on memberp.id = m.member_id       inner join principals linkp on m.principal_id = linkp.id) as mp   on mp.linkuri like concat(i.principaluri, '%') where mainp.uri = 'principals/test' or mp.memberuri = 'principals/test' 	0.223824561922588
14346501	5358	sql combine only some duplicates	select acct, date, sum(bal) as bal from dbo.tets73 group by acct, date, case when acct != 123 then bal end 	0.00891188568926497
14354958	30536	how to get the refresh job id by mview name?	select m.*, r.job   from dba_refresh r        inner join dba_refresh_children rc                on rc.rowner = r.rowner               and rc.rname = r.rname        inner join dba_mviews m                on m.owner = rc.owner               and m.mview_name = rc.name; 	0.00242815295903035
14388790	16087	sort posts by newest child's timestamp or own timestamp	select  *,         (         select  coalesce(max(cp.post_date), ct.post_date)         from    conversation_conversationpost cp         where   cp.thread_id = ct.id         ) as sort_date from    conversation_conversationthread ct order by         sort_date desc 	0
14389125	13104	multiple filters on sql query	select  item, qty_in_stock from    (         select  *,                 row_number() over (partition by item order by item_date desc, sequence desc) rn         from    mytable         where   item_date <= @date_of_stock         ) q where   rn = 1 	0.356341818134676
14389170	22610	join two tables with multiple foreign keys	select  t.tripid_pk, ls.name startlocationname, le.name endlocationname from    trips t join    locations ls on      ls.locationid_pk = t.startlocationid_fk join    locations le on      le.locationid_pk = t.endlocationid_fk 	0.00147722916870581
14395410	19318	mysql query to select users from a table who have the most entries	select user_id,count(user_id) as cnt from table group by user_id order by cnt desc limit 0,3; 	0
14416684	19717	get entry by entry	select a.id as articleid, a.description as articledescription, a.supplierid, s.description as supplierdescription from articles a inner join supplier s on a.supplierid = s.supplierid where a.id = 1 	0.000226280844760008
14441888	20788	more than one join mysql?	select * from sub_menu left join root_sub on sub_menu.id = root_sub.sub_id left join root_menu on root_sub.root_id = root_menu.id 	0.0837991158431074
14444872	34205	how to join multiple tables in mysql?	select distinct concat(c.fname," ", c.lname) as fullname, s.description from customer c  inner join orders o on c.customer_num = o.customer_num inner join items i on o.order_num = i.order_num inner join stock s on s.stock_num = i.stock_num where i.manu_code = 'anz' 	0.113966980035863
14445439	24912	find items that don't have any entries in the link table with mysql	select      items.* from items left join user_tags on items.id = user_tags.item_id left join tags on user_tags.tag_id = tags.id where tags.title in ($array_of_tags) and user_tags.tag_id is null; 	0
14446290	13780	how to seperate data from a row and count each data using mysql	select q1.chr, count(*), q2.cnt from ( select substr(c1, 1, 1) as chr from tab        union all        select substr(c1, 2, 1) as chr from tab        union all        select substr(c1, 3, 1) as chr from tab      ) as q1,      ( select count(c1) as cnt from tab ) as q2 where q1.chr != '' group by q1.chr 	0
14446860	38242	sql query in a table but same id	select  * from (select  *,rank () over ( partition by  tp_id order by   tp_version desc) as rnk         from    yourtable         ) mytable where rnk <= 1 	0.00173408801962607
14449500	39932	selecting (sku)s and (qty)s using php($sql) which (sku)s are in table a but not in table b	select sku, qty from tablea where tablea.sku not in (select sku from tableb) 	0.000511619647863289
14459298	2728	how do i select records between two date & times?	select o.order_id,c.client_name,c.client_lname,o.total_amount,o.order_date,o.order_time from orders as o join client as c on o.client_id=c.client_id where  date_add(o.order_date, interval o.order_time hour_second) between '2012-12-03 11:06:54' and '2013-01-19 01:07:10'  and o.order_status='1' order by o.order_id 	0
14462863	12905	multiple selects on one query	select * from calendar where calendarid = 256     and (private = 0 or (private = 1 and privateid = 11)) 	0.058933956228645
14480856	13722	get distinct result	select    p.productid,    case when count(r.firstproductid) > 0         then 'linked'         else 'not linked'    end relation from product p    left join productrelation r       on p.productid = r.firstproductid         or p.productid = r.secondproductid group by p.productid 	0.0133063904739979
14527903	23230	find duplicate values in oracle	select * from ( select col1,  col2,  count(col1) over (partition by col1) col1_cnt from table1  ) where col1_cnt > 1  order by 2 desc; 	0.00261274022884125
14543048	15029	how to get sum of entries having cats, subcats and 2 tables	select a.*, b.sum_subcat from table1 a inner join  (   select t2.parent, sum(entries) sum_subcat   from table1 t1 inner join table2 t2    on t1.catid = t2.id    group by t2.parent )b on a.catid = b.parent where a.catid = 57; 	0
14554471	24393	firebird cast integer as time or date	select dateadd(second, colamountofseconds, cast('00:00:00' as time))   from mytable; select cast(cast('2013-01-01' as timestamp) + cast(colamountofseconds as double precision) / 86400 as time)   from mytable; 	0.154492000048587
14557326	7616	sql server select case statement with two distinct value in two columns	select  case when vmf is null then 0 else 1 end as vmf,  case when srr is null then 0 else 1 end as srr,  upccode,date, storeid from (select itemid,items.upccode, servicetype, date, row_number() over (order by servicetype) as rownumber, s.id as storeid            from items join schedule on items.upccode= schedule.upccode ) r pivot ( max (r.rownumber) for r.servicetype in( [vmf],[srr]) ) as pvt 	0.0057124258933214
14565360	39946	how user search can be done using name?	select * from table where first_name like '%john%' or last_name like '%doe%' 	0.682350253505412
14577150	9883	select count from multiple tables and group by one field	select t.user_id,t.type, max(users.user_name), sum(t.cnt) from ( select user_id,type,count(*) cnt from data_table_2012_10 where date_time between date1 and date2 group by user_id,type union all select user_id,type,count(*) cnt from data_table_2012_11 where date_time between date1 and date2 group by user_id,type union all ......................................... union all select user_id,type,count(*) cnt from data_table_2013_02 where date_time between date1 and date2 group by user_id,type ) t left join users on (t.user_id=users.user_id) group by t.user_id,t.type 	0.000124560404339333
14581041	28003	i want to display my result of query like that	select      case when _no = @i then '' else @i := _no end     as row_no,     _no,     _name from (     select 1 as _no, 'vikas' as _name union all     select 1, 'kratika' union all     select 2, 'vikas'  ) t, (select @i := '') temp 	0.0384790285822004
14591083	11972	how to get the value of a mysql variables var?	select variable_value   from information_schema.global_variables  where variable_name = 'version'; 	0.000656444227999283
14597101	20127	plsql date filter error	select ('[' || to_char(work_date, 'dd-mon-yyyy') || '] ' || field_name || ' - ' ||work_desc) d from daily_work where work_date >= to_date('30-jan-2013','dd-mon-yyyy') - 31 order by work_date desc 	0.733256842939526
14604188	32250	mysql include column with no rows returned for specific dates	select   t.`date`,   c.name,   sum(t.trans_in) as 'input' from customers c left join trans t on (c.name = t.customer and t.`date` >= '2013-01-24') where c.name in('george','nick','ted','danny') group by c.name order by input desc; 	8.67311376350791e-05
14607240	12228	query to get data dependent on another column, but only if it appears once	select * from   mytable where  state = substr(id, 1, 2) or        name in (select name from mytable group by name having count(*)=1) 	0
14608944	2919	sql select values associated with keys from other table	select a1.value, a2.value, a3.value  from tableb  join tablea as a1 on tableb.col1 = a1.key  join tablea as a2 on tableb.col2 = a2.key  join tablea as a3 on tableb.col3 = a3.key; 	0
14609166	35302	two tables relationship based on conditions	select distinct pr.sku, pr.title, pr.weight_gm, min(po.postal_charges) as po_charges from products pr    join postage po on pr.weight_gm <= po.weight_gm group by pr.sku, pr.title, pr.weight_gm 	0.000326022837060386
14639184	8993	query results as comma-delimited string without using pivot?	select stuff( (select ',' + s.elementname from tablename s for xml path('')),1,1,'')  union all select stuff( (select ',' + s.value from tablename s for xml path('')),1,1,'') 	0.47929164289103
14653257	12289	how to get the row with max timestamp in postgres?	select usr, event_dt from mytable order by event_dt desc limit 1 	9.17016895133932e-05
14678294	36680	mysql - displaying avg on more than just one row	select field1,field2,(select avg(field2) from table) as avgfieldtwo from table 	0.00102604052779678
14693637	32491	how to write a query by including the null values too	select sum(cash)  from bought_cash where uid = 1 and (source is null or source not in ('a', 'b')) 	0.229013061901425
14701296	25242	how to use max and top in sql query in oracle?	select id      , item      , quantity      , date   from (select id              , item              , quantity              , date           from your_table          order by quantity desc, date desc         ) where rownum = 1 	0.276251020446577
14708741	16333	how to find inherited columns?	select relname as table_name, attname as column_name  from pg_class  join pg_inherits on pg_class.oid = pg_inherits.inhrelid join pg_attribute on pg_inherits.inhparent = attrelid where attnum > 0; 	0.00311947076453156
14731476	18401	oracle pivot and sequencing with multiple columns	select node,        max( case when rn = 1 then dur else null end ) dur1,        max( case when rn = 2 then dur else null end ) dur2,        max( case when rn = 3 then dur else null end ) dur3 from (select substr(arg_string,1,4) node,              substr(numtodsinterval(end_time-start_time,'day'), 12, 8) dur,              row_number() over (partition by substr(arg_string,1,4)                                 order by substr(arg_string,1,4), start_time) rn       from pro.program_status       where  prog_name like ('%v8x-6%')         and  start_time > sysdate - 10) group by node 	0.239759416976216
14734073	36168	select entries by day over the last 7 days	select  date(from_unixtime(columname)), count(id) totalcount from    tablename where   date(from_unixtime(columname)) between curdate() + interval -7 day and curdate() group   by date(from_unixtime(columname)) 	0
14739134	23598	sql query to find false negatives w.r.t data matching or entity resolution	select        t1.id,        t1.variable,        t1.value     from        table t1     where        exists ( select 1                    from t2                    where t2.id != t1.id                      and t2.variable == t1.variable                      and t2.value != t1.value) 	0.213532859867176
14742369	11325	sql: sum the sum of max values of results returned	select t.post_id,        sum(maxpostmetric) as sumvalue    from (      select post_metrics.post_id,      post_metrics.post_metric_type_id,      max( post_metrics.value ) maxpostmetric      from post_metrics      inner join posts on posts.id = post_metrics.post_id      where posts.channel_id = 2268     group by post_metrics.post_id, post_metrics.post_metric_type_id      order by post_metrics.id    )t  inner join post_metric_types on post_metric_types.id = t.post_metric_type_id  group by t.post_id 	0.000134367789672702
14752491	27494	sql select all in table that have same id as '..'	select *  from <table>  where deptid=(               select deptid from <table> where userid=3              ) 	5.46786818402243e-05
14754693	10947	need daily count of whole month - sql2008	select cast(timestamp as date) as [date], count (*) as numfailedtests from students  where message like 'failed test.%' and timestamp between '2013-01-01' and '2013-01-31' group by cast(timestamp as date) order by cast(timestamp as date) 	0.000663107682543221
14756067	17937	converting nvarchar to date column	select * from tablename where isdate(columnname) != 1 	0.0664693543982116
14763922	28848	counting events over flexible ranges	select id          , target_date          , event_date          , count(*) as n          , sum(case when event_date between target_date-365 and target_date-1                      then 1                     else 0                 end) as prior_           , sum(case when event_date between target_date+1 and target_date+365                      then 1                     else 0                end) as after_                     from subsample_table i       left join             event_table h         on i.id = h.id         and i.target_date = h.event_date      group by id, target_date, period 	0.00625601102814278
14771164	36557	mysql writing image blob to disk	select   data_column from   table1 where   id = 1 into dumpfile 'image.png'; 	0.723442624592362
14776811	6994	query in mysql to show available balance + 5% in certain accounts	select a.accountnumber,       a.anyothercolumnsyouwanttoshow,       a.avail_balance * 1.05 as availplus5percent    from       account a    where       a.product_cd = 'cd'; 	0
14825309	24220	mysql - order by values in separate table	select table1.*, max(table2.time)  from table1  inner join table2 on table1.otherid = table2.otherid group by table2.otherid order by table2.id 	0.00490946675096553
14829972	18167	split string using pl/sql using connect level on null value	select cast(regexp_substr (str, '(.*?)(~|$)', 1, level, null, 1) as char(12))  output from (select 'how~do~i~do~this' as str from dual) connect by level <= regexp_count(str, '~') + 1; 	0.0561678425177973
14839090	30589	use sql to generate string	select   id, user, num, type, seq from ( select   sample.*,   @row:= case when @lst_type=type                    and @lst_user=user                    and @lst_num=num then @row+1 else 65 end,   concat(type, num, char(@row)) seq,   @lst_type:=type,   @lst_user:=user,   @lst_num:=num from sample, (select @lst_type:=null,                      @lst_user:=null,                      @lst_num:=null,                       @row:=65) r order by id ) s 	0.236365751369036
14854386	10324	select n random rows per specified group	select id,name,report_id from ( select *, @row:=if(name=@name,@row,0)+1 as rn, @name:=name from  (select *,rand() as trand from t) t1, (select @row:=0,@name:='') tm2  order by name,trand ) t2 where rn<=10 	0
14858404	37675	join 2 tables without records replication	select *  from table1 left join table2 on table1.id = table2.related_id group by table1.id 	0.0194718224650904
14873695	10466	sphinxql - how to order by date without a search query	select * from cars order by date desc limit 0, 20; 	0.0886893729925992
14879784	947	select to return all items in one row	select      [item_id],      stuff(          (select ',' + [item]           from tablename           where [item_id] = a.[item_id] and item_id = 82           for xml path (''))           , 1, 1, '')  as nameslist from tablename as a where item_id = 82 group by [item_id] 	0
14886846	9839	select value from table because two conditions are not met	select  count(*) totalcount from    ts_room a         inner join ts_roompref b             on a.id = b.room_id         inner join ts_request c             on b.request_id = c.roompref_id where   c.day_id = 1 and c.period_id = 1 	0.000492155843277389
14891670	38790	how to find column names across various table	select distinct table_name  from information_schema.columns where column_name like '%keyword_to_search%'  and table_schema='your_database_name'; 	0
14897258	33399	need mysql query to fetch alternate records from database	select item,description,brand from (select a.item, b.description, b.brand, case b.brand         when @curbrand          then @currow := @currow + 1          else @currow := 1 and @curbrand := b.brand end       as rank from a inner join b on a.id=b.a_id join (select @currow := 0, @curbrand := '') r ) t order by t.rank,t.brand; 	0.0111893985618368
14900981	16747	how can i program a keyboard shortcut to select top 1000* from selected table?	select top 1000 * from 	0.00742575455872843
14901661	23705	selecting two colums in two tables (one column being the same in both tables)	select   category_name,   group_concat(subcategory_name) from   category inner join subcategory   on subcategory.id_category=category.id_category group by   category_name 	0
14907701	23474	get the count value as per the product from table	select id, product, sum(reactions = 'bad') as bad, sum(reactions = 'good') as good,     sum(reactions = 'normal') as normal from yourtable group by product 	0
14910769	37171	subquery in a loop	select ms.status_id,    ms.member_id,    ms.status_text,    ms.status_time,    cs.comm_text,    cs.comm_time from message_status ms   left join comments_status cs on cs.status_id = ms.status_id where ms.member_id = memberid order by ms.status_id desc, cs.comm_time desc limit 20 	0.673622162795882
14912484	26935	user id to username mysql in leaderboard	select wp_users_score.id,         wp_users.user_id    from wp_user_score   inner join wp_users           on wp_user_score.id = wp_users.user_id   where wp_users_score.id = $id; 	0.0519227513310659
14919825	36947	select records that start with special letter	select * from tbl where col like '%z%' order by charindex('z', col) 	0.00134253376363852
14923077	18580	how to select from union result?	select * from (     select ... from ... where ...     union all     select ... from ... where ... ) as something; 	0.0210032563186578
14930756	38593	is there any other logical or more robust way	select  count(case when salary >= 0 and salary <= 1000 then salary end) "salary >= 0 and salary <= 1000",         count(case when salary >= 1000 and salary <= 10000 then salary end) "salary >= 1000 and salary <= 10000",         count(case when salary >= 10000 and salary <= 100000 then salary end) "salary >= 10000 and salary <= 100000" from    user_details 	0.690814329679021
14934427	12017	returning a set of hstore values as a set of records of a table type	select   (populate_record(null::public.usr, logged_actions.row_data)).* from   audit.logged_actions where   audit.logged_actions.table_name = 'usr' 	0
14945796	6928	algorithm/query to get statistical data from table using php/mysql	select val, count(val) as frequency from  (select num1 as val from test  union all  select num2 as val from test  union all  select num3 as val from test  ) as b group by val order by frequency desc limit 2 	0.00131427779505603
14981766	4603	get information about all rows from one table, when in join table that row is not	select  `users`.*, `useritems`.*, `moduleitems`.*, `modulesubitems`.*  from    `users`         cross join `moduleitems`         left join `useritems`          on useritems.f_user_id = users.user_id         and moduleitems.moduleitem_id = useritems.f_moduleitem_id         left join `modulesubitems`          on modulesubitems.modulesubitem_id = useritems.useritem_value 	0
14984220	7351	avoid repeatation of rows for every instance when joined with a table	select cstid,         max(cstdetails) cstdetails,         max(cstgroupid) cstgroupid,         max(cstnoteid) cstnoteid,         max(cstnote) cstnote,         max(cstgroupnoteid) cstgroupnoteid,         max(cstgroupnote) cstgroupnote from (select c.cstid,          c.cstdetails,         0 cstgroupid,         n.notesid cmbnotesid,         n.notesid cstnoteid,         n.notetxt cstnote,         0 cstgroupnoteid,         '' cstgroupnote  from customer c  left outer join customernotes n on c.cstid = n.cstid  where c.customertypeid = 1  union all  select c.cstid,         c.cstdetails,         r.cstgroupid,         n.notesid cmbnotesid,         0 cstnoteid,         '' cstnote,         n.notesid cstgroupnoteid,         n.notetxt cstgroupnote  from customer c  left outer join customerrelationship r on c.cstid = r.cstid  left outer join customernotes n on r.cstgroupid = n.cstid  where c.customertypeid = 1) u group by cstid, cmbnotesid 	0.000401247791985384
14984782	20811	how do i get top 5 score in mysql	select s.* from student as s   join     ( select distinct score       from student       order by score desc           limit 5     ) as lim     on s.score = lim.score  order by s.score desc ; 	0.000653281489110117
15000109	41046	how to join 3 table with this condition?	select  t.id_customer, c.name,          count(t.id_customer) as total_transaction,          sum(t.qty) as purchase_qty from transaction t inner join customer c on t.id_customer = c.id_customer group by t.id_customer,c.name 	0.591963409729838
15005916	37608	get number of rows returned in mysql query	select count(*) from (select count(l.product_number_language) as counts, l.id, l.product_number, l.language,    l.product_number_language from bs_products_languages l left join bs_products p on (l.product_number_language = p.product_number) where l.product_number = 'c4164'  and l.active='y' and p.active='y' group by l.language) as t 	0.000116170001273939
15018391	11576	grouping on multiple columns	select max(idx), src_path, dest_path, max(code)  from yourtable group by src_path, dest_path 	0.0101342201338982
15018582	22520	how to concatenate two or more strings in sql server 2008 r2?	select shipsite, ratingmonth, prior, revised, comments = stuff((   select char(13) + char(10) + comments     from dbo.yourtable as x2        where x2.shipsite = x.shipsite       and x2.ratingmonth = x.ratingmonth       and x2.prior = x.prior       and x2.revised = x.revised     for xml path, type).value('.[1]','nvarchar(max)'), 1, 2, '') from dbo.yourtable as x group by shipsite, ratingmonth, prior, revised; 	0.107398542751445
15023133	23878	sql result set merge	select   [agent], [transdate],  [recipt no], [customer name], [order no] , [trans no] , quantity,  [amount cost], sum ( quantity ) over () as [sum of quantity] ,  sum ( [amount cost] ) over () as [sum of amount cost] from [customer] c 	0.048782846888497
15029122	7646	inner array in mysql query result to php	select  a.*, b.id_rv, b.date_uploaded from    records a         inner join records_values b             on a.id_record = b.id_record 	0.552135739032104
15049688	11127	selecting the maximum bids overall	select userid, uname from user1  where userid in  (select bidder from bid group by bidder having count(bidder) =  (select max(c) from (select count(*) as c, bidder from bid group by bidder))); 	0.00119734864078261
15053941	13242	sql sales report by calendar week	select o.date_purchased, concat(year(o.date_purchased), lpad(week(o.date_purchased), 2, '0')) as weekyear, op.products_id, sum( op.products_quantity ) from orders_products op left join orders o on op.orders_id = o.orders_id where op.products_id = 331 group by weekyear order by weekyear 	0.00622202512874381
15071002	18884	mysql divide two values from same column	select metalid,   max(case when currencyid = 1 then fixam end) /    max(case when currencyid = 2 then fixam else 1 end) output from fixes group by metalid 	0
15072248	32241	find table from querying column name in oracle sql developer	select * from all_tab_columns  where column_name like '%task%'  and owner = 'database_name'; 	0.00112118749732092
15072544	8966	mysql combining multiple tables in a view	select strtitle as 'title', txtcontent as 'content', 'tblcontent' as 'from'  union       select news_title as 'title', news_content as 'content', 'tblnews' as 'from'  union  select company_title as 'title', company_content as 'content', 'tbltrademembers' as 'from' 	0.0565673428309798
15080861	14659	distinct on two columns (separately) and min on another column	select distinct t.master_id,   t.slave_id,   t.distance from join_table t inner join (   select id, min(distance) dist   from    (     select master_id id, min(distance) as distance     from join_table     group by master_id     union     select slave_id id, min(distance) as distance     from join_table     group by slave_id   ) src   group by id ) md   on t.distance = md.dist   and (t.master_id = md.id or t.slave_id = md.id) 	0
15085239	2342	oracle working with unix timestamp	select * from sessiondata where modified between (sysdate - to_date('01-jan-1970','dd-mon-yyyy')) * (86400) - 120 and (sysdate - to_date('01-jan-1970','dd-mon-yyyy')) * (86400); 	0.331615067140873
15094119	23249	count number of all status and specific status with partition	select left_to_right.lid,        count(distinct left_to_right.rid) all_right_data_statuses,        count(distinct case when right_data.status = 1 then left_to_right.rid                        else null end) right_data_status_1 from     left_to_right   join     right_data   on     right_data.rid = left_to_right.rid group by left_to_right.lid 	0
15119901	21418	unique count (print out 0) within time range	select     ((time - 1) / 2) + 1 as newtime,     count(distinct case when state = 'dc' then user_id end) as count from ...  group by ((time - 1) / 2) + 1 	0.000123105757093438
15134416	8516	mysql get subquery value	select   sum(timecode) as tc_sum,   sum(timecode) as cnt,   abs( sum(timecode) / sum(timecode) - '".$timecode."' ) as distance,   round(sum(timecode) / sum(timecode)) as centr from dados d where tag = 'donald'  and filename = 'donald.mp4'  and group_id = '1' 	0.0286932737157968
15138270	19372	how to get the occurrence frequency of sql result?	select cnt, count(*), min(publisher), max(publisher) from (select publisher, count(*) as cnt       from t       group by publisher      ) t group by cnt order by 1 	0
15152217	14483	select the top x rows from a table ignoring the first y rows	select * from   persons limit  10, 10 	0
15156000	15683	how to write correct query to find students not currently in a course	select s.studentid, s.forename from student s where s.studentid not in (select studentid  from  student_course c where c.courseid = 1) and s.active = 1 	0.090981797354836
15156267	4642	sql server 2005 : putting a gap in 'group by' results	select  column1, otherinfo from    (   select  column_1 = cast(column_1 as nvarchar),                      otherinfo = cast(other_info as nvarchar),                      sort1 = row_number() over(order by column_1),                      sort2 = 1             from    some_table               group by column_1, otherinfo             union all             select  column_1 = n'',                     otherinfo = n'',                     sort1 = row_number() over(order by column_1),                     sort2 = 2             from    some_table               group by column_1, otherinfo         ) d order by sort1, sort2; 	0.530465106471057
15158983	3269	searching oracle database using a "contains" query instead of an "exact match" query	select * from userinfo where uname like '%key%' 	0.0383676453778759
15178181	14156	mysql list profiles and movies using complex joins in one query but three tables	select  profile_tbl.*, movies_tbl.*  from (      select distinct id from profile_tbl limit 10     ) limittable     inner join profile_tbl on profile_tbl.id=limittable.id     left join profile_movies_rel_tbl         on profile_movies_rel_tbl.profile_id = profile_tbl.id     left join movies_tbl         on profile_movies_rel_tbl.movie_id = movies_tbl.id 	0.264687880408494
15178625	5693	sql server 2005 date formatting [dd-mon-yy hh:mm:ss]	select convert(varchar(20),[somedate],113) 	0.523428862534761
15184006	30262	how to get time value for multiple max/min values in query	select quote_date   ,min(dema_supb) as mindemasupb   ,(select total_time from [dbo].[a_b_ratiotable] where quote_date = r.quote_date and dema_supb = min(r.dema_supb)) mindemasupbtotal   ,max(dema_supb) as maxdemasupb   ,(select total_time from [dbo].[a_b_ratiotable] where quote_date = r.quote_date and dema_supb = max(r.dema_supb)) maxdemasupbtotal   ,min(supa_demb) as minsupademb   ,(select total_time from [dbo].[a_b_ratiotable] where quote_date = r.quote_date and supa_demb = min(r.supa_demb)) minsupadembtotal   ,max(supa_demb) as maxsupademb   ,(select total_time from [dbo].[a_b_ratiotable] where quote_date = r.quote_date and supa_demb = max(r.supa_demb)) maxsupadembtotal   ,min(demb_supa) as mindembsupa   .......   ,max(demb_supa) as maxdembsupa   ,min(supb_dema) as minsupbdema   ,max(supb_dema) as maxsupbdema   from [dbo].[a_b_ratiotable] r   group by quote_date 	0.000631080076564101
15185043	27657	how to restrict the right table in a left join to a single row (with preference of a particular row)?	select  c.rateid,          c.providerid,          new1.ratetype,          new1.pricing_information from    currentcalls as c         left join custprices d             on c.rateid = d.rateid         left join          (             select  a.*             from    costprices a                     inner join                     (                         select  ratetype, max(x.providerid) min_provid                         from    costprices x                                 inner join currentcalls y                                   on x.providerid in (y.providerid, 0)                     ) b on  a.ratetype = b.ratetype and                             a.providerid = b.min_provid         ) as new1 on new1.ratetype = d.ratetype; 	0.000165571195767415
15240363	37043	how to subtract two dates with criteria (if data is not existing in another table, use date today, if existing, use the date in there)?	select t1.caseno, t1.lastname + ', ' + t1.firstname as fname , case      when t2.caseno is null          then datediff(day,cast(t1.datepiconsult as datetime), getdate())      when t2.med_stat not in ('fit to work',                              'deceased',                              'reached maximum medical cure',                              'stop treatment')            then datediff(day,cast(t1.datepiconsult as datetime), getdate())      else       datediff(day,cast(t1.datepiconsult as datetime),cast(t2.med_stateff as datetime))   end as treatmentdays  from data2002.dbo.tblcrew as t1 left join eds.dbo.tblpms as t2  on t1.caseno collate database_default = t2.caseno collate database_default 	0
15255633	26258	postgres select group by most selling item by publisher	select     distinct on (pub_name),     pub_name,     book_name,     selling from (     select         publisher.pub_name,         book.book_name,         sum(rank.selling) selling     from         publisher         inner join          book on book.id_pub = publisher.id         inner join         rank on rank.id_book = book.id     group by 1, 2 ) s order by pub_name, s.selling desc 	0.00240081405982858
15265051	20536	sql query:not able to group data from different tables	select  case when gender='m' then 'male'              when gender='f' then 'female'        end as gender, sum(t.std1) as [students(standard1)], sum(t.std2) as [students(standard2)], sum(t.std3) as [students(standard3)] from tblcandidateinfo as c join ( select candid, 1 as std1, 0 as std2, 0 as std3  from tblstandars1students union all select candid, 0 as std1, 1 as std2, 0 as std3  from tblstandars2students union all select candid, 0 as std1, 0 as std2, 1 as std3  from tblstandars3students ) as t on (c.candid=t.candid) group by gender 	0.00189984264589198
15282156	18502	select only employees with the job title waiter	select * from myemployees where jobtitle='waiter' 	0.00165576312277872
15284539	9285	summing order totals mysql	select s.storeid, s.storenum, s.name        sum((1+0.07125)*i.qty*i.discprice) as total from items as i left join orders as o      on i.orderid=o.orderid left join stores as s      on o.store=s.storeid where o.date >= '2012-01-01'   and o.date < '2013-01-01' group by s.storeid, s.storenum, s.name; 	0.134335257086571
15291855	13649	how to determine which unique index enforces the primary key in oracle	select     owner, constraint_name, table_name, index_name  from     user_constraints  where constraint_type in ('p'); 	0.00101219215264426
15291875	4889	i want to add zeros in the column of the sql database and amke it of 3 digit	select right('000' + cast(1 as varchar(3)), yourcolumnnamehere) as value 	0
15292129	11482	get number of duplicate rows resulting from a distinct query	select a,b,c,count(*) from table group by a,b,c 	0
15317410	40470	count total of each activity type - oracle - sql	select a.type_of_activity, count(ba.individual_id) from book_activity ba join events e   on e.event_id = ba.event_id join activities a   on a.activity_code = e.activity_code group by a.type_of_activity; 	9.2034831530381e-05
15324611	22523	selecting concat with the %-tag exculding one character	select * from table where mycolumn like 'abc%' and mycolumn not like '%/%' 	0.00562507458510991
15328941	9620	sql inner join issue with getting exact value by id	select `type`  from `data_user` table1  inner join `user_type` table2 on (table1.username = 'sber' and      table1.id = table2.id) 	0.395663099442363
15332779	14105	get the last record in each group in mysql singular table, with criteria that ignores certain groups	select  a.* from    aliissales.tblmovedactual a         inner join         (             select  max(keynum) xx, paymentid, buyerid             from    aliissales.tblmovedactual             group   by paymentid, buyerid         ) b on  a.paymentid = b.paymentid   and                 a.buyerid = b.buyerid and                 a.keynum = b.xx 	0
15360788	10795	need mysql idiom for checking whether string contains any of a set of characters	select id, name from mytable  where name not rlike '[;.<>#$!]'; 	0.000874249866540926
15367573	1242	get the max length allowed in column, mysql	select column_name, character_maximum_length  from information_schema.columns where table_schema = database() and          table_name = 'turno' and               column_name = 'nombreturno'      	0.0116986303275734
15370812	39878	take away the exists but leave in the switch	select * from   #data d        except        select myfield from #exclusions where @showall <> 1; 	0.0500279414825658
15375117	19452	mysqli best way to select related items from two separate tables	select `pages_id`, pages.title, match(`content`) against('search term' in boolean mode) as score  from `pagecontents` join pages on pagecontents.pages_id = pages.id  where  match(`content`) against ('search term' in boolean mode)  order by score desc; 	0
15376071	28016	select query for two bits of data	select     ud1.value as gender,     ud2.value as age,     count(*) as c from userdata ud1 join userdata ud2 on     ud1.userid = ud2.userid and     ud2.property = 'age' where ud1.property = 'gender' group by gender, age 	0.00954177716241264
15376298	8368	null table adapter value with if then statement	select        count(sterminal) terminal from            swipe where        (dtcreated between @startdate and @enddate) and (sterminal = 'swiper 1') having count(sterminal) > 0 	0.127568226342769
15376594	17996	simple sql order by position	select id, position from pages order by position 	0.777101903582942
15380988	14682	duplicate rows in sql statement	select   id, firstname, surname        , max(monday) as monday,  from ( your giant query ) as q group by id, firstname, surname 	0.0279657046410672
15382708	11904	sql select multiple rows with same column values	select [column1], [column2], [column3], [column4] from (   select [column1], [column2], [column3], [column4],     row_number() over(partition by column2, column3, column4 order by column1) rn   from yourtable ) src where rn <= 3 	0.000155167656876519
15382813	25895	unknown column in field list - division	select count(*) as numero_propostas,           total as total,           (count(*) / total) as divisao     from consultaartigos2 as ca 	0.0418912410862555
15383777	33195	how to handle subquery which returns more than one row	select * from `package_reviews` r left join `wp_posts` p on r.post_id= p.post_id where p.post_author = 1 	0.00554885815430017
15388683	27768	selecting data from keyword columns in sql ce	select     table_name,     table_schema,     index_name,     [clustered],     [unique],     column_name from information_schema.indexes 	0.00698371657685142
15392266	5714	empty table by using not exists	select g.name, s.hour, gs.weekday from schedule s inner join group_schedule gs  on gs.schedule_id = s.id and group_id = 6  inner join groups g on g.id = gs.group_id order by g.name, gs.weekday 	0.309248462338489
15393798	13843	sql: sum the count and group to combine queries	select a.*, b.* from (   select   posts.channel_id,   posts.contenttype,   count(posts.contenttype) as contenttypecount   from posts   inner join channels on channels.id = posts.channel_id   where channels.site_id = 1003   and channels.channel_type_id = 1   group by posts.channel_id, posts.contenttype ) a join (   select   count(posts.id) as total   from posts   inner join channels on channels.id = posts.channel_id   where channels.site_id = 1003   and channels.channel_type_id = 1 ) b on 1=1 	0.0202899365941218
15403296	35959	plsql code to replace values of a column with characters	select name,substr(lpad(name,length(name)+length(name),'x'),1,length(name)) as replaced_name from table 	0.0313724595247614
15403694	23852	mssql 2005 query group dates - even dates with no records?	select table_cal.day_diff as "day",   coalesce(table_count.base_count,0) as "active cases" from (select distinct datediff(dd, getdate(), ibase.createdon) as day_diff      from [dbo].[incidentbase] ibase) table_cal left outer join (select datediff(dd, getdate(), ibase.createdon) as day_diff,     count(ibase.createdon) as base_count     from [dbo].[incidentbase] ibase     where ibase.statuscode not in (5,6) and ibase.casetypecode in ('200000','200005','200006')     group by datediff(dd, getdate(), ibase.createdon)) table_count on (table_cal.day_diff = table_count.day_diff) order by table_cal.day_diff desc 	0.00382974977752125
15417158	13261	sql join with 2 conditions	select     c1.page_id, p.name, c1.name, c2.name from     pages p     inner join     categories c1 on p.id = c1.page_id     inner join     categories c2 on p.id = c2.page_id where     c1.name = 'nice' and c2.name = 'supper' 	0.383100616337087
15424292	16429	get partial weeks when generating series in postgresql	select generate_series(date_trunc('week', '2013-03-01'::date + 6)                       ,date_trunc('week', '2013-03-14'::date)                      ,'1 week')::date as day union  select '2013-03-01'::date order  by 1; 	0.00743603726399336
15424950	19876	query to select a start and stop time	select min(t1) t1, t2 from (     select s1.time t1, min(s2.time) t2     from mytable s1     join mytable s2       on s1.on   < s2.on      and s1.time < s2.time     group by s1.time ) x group by t2 	0.0779074518126863
15434503	39195	adding zero when concatenating year and month	select convert(varchar(4), s_yr)     + right('0'+ convert(varchar(2), s_mnt),2) as year_month 	0.000447458800389394
15442972	29713	is it possible to compare date ("y-m-d h:i:s") with time() inside mysqli_query?	select *  from posts  where post_date > date_sub(now(), interval 1 day)  order by likes desc  limit 10 	0.127648782825075
15449347	26068	inner join? pulling info from 2 tables - webmatrix/razor	select ownerinfo.firstname, ownerinfo.lastname  from ownerinfo inner join propertyinfo on propertyinfo.ownerid = ownerinfo.ownerid where propertyinfo.propertyid='@0' 	0.00225053178451816
15453671	36606	sql select date from second table if id matches	select s.security_id, nvl(c.odate, s.maturity_date) as maturity_date from security s left join callput c on s.security_id = c.security_id 	0
15461627	23278	how to filter a table	select * from    network_users  a,          network_users  b where   a.userid    =   b.relateduserid and     b.userid    =   a.relateduserid 	0.0289111551435829
15478974	38793	loop through mysql table and output in particular order with php	select              *         from              table         where             spec=:spec         order by car_name=:user_car desc, car_name asc 	0.0949787477218333
15481848	18124	select from xml with unknown structure	select @sql = 'select '+stuff(       (       select ',t.n.value('''+t.n.value('local-name(.)', 'sysname')+'[1]'',''varchar(max)'') as '+ t.n.value('local-name(.)', 'sysname')+',  t.n.value(''('+t.n.value('local-name(.)', 'sysname')+'/@title)[1]'+''',''varchar(max)'') as '+ t.n.value('local-name(.)', 'sysname')+'@title'       from @xml.nodes('/*[local-name(.)=sql:variable("@knownname")]/*') as t(n)       for xml path(''), type       ).value('.', 'nvarchar(max)'), 1, 1, '')+       ' from @xml.nodes(''/*[local-name(.)=sql:variable("@knownname")]'') as t(n)' 	0.20998184170971
15485802	17718	mysql sum and group by with data identifying info in second table	select f_user.first, f_purchases.compid, f_purchases.userid, sum( f_purchases.amount ) as total from f_purchases, f_user where f_purchases.compid = f_user.compid and f_purchases.userid = f_user.userid group by f_purchases.compid, f_purchases.userid 	0.000185657202125983
15492646	1798	inner join with 3 tables	select  a.*, c.date from    album a         inner join album_photo b             on a.album_id = b.album_id         inner join photo c             on b.photo_id = c.photo_id where   c.nick = 'owner' and         (           select count(*)            from   album_photo d           where  b.album_id = d.album_id and                  d.nick = 'owner' and                  b.date >= d.date         ) <= 2 	0.602917904392728
15492856	23094	using sql where to perform and or then and comparison of results	select stuff   from table   where (variable1 = 'value' or variable2 = 'value2')     and variable3 like '%value3%' 	0.671728003872981
15506512	32290	select count across one-to-many relationship	select t.teamid, count(p.team) player_count from team t left join      player p on p.team = t.teamid group by t.teamid 	0.049950006397646
15507617	17101	union all - 3 tables, 2 will never contain duplicates, the other will	select * from table1 union all   select * from table2 union all   select *   from (     select distinct * from table3   ) t 	0.000332267555324669
15530102	7313	show mutiple tables on a query	select * from tweets inner join users on tweets.user_id = users.user_id 	0.0114186005167044
15530123	26390	linking two mysql tables	select p.name, p.id as player_id, b.creator_id as creator_id from banhammer_bans as b inner join banhammer_players as p on p.id = b.player_id 	0.0061127398476531
15530947	18098	mysql query to find the name and age of the youngest employee in each department	select e2.ename, e2.age, w2.did from emp e2  join works w2 using (eid) join (select w.did, min(e.age) as youngest       from works w        inner join emp e using (eid)       group by w.did) sq   on w2.did = sq.did and e2.age = sq.youngest 	0
15540297	2673	get count of multiple condition	select sum( if( rr <3, 1, 0 ) ) as da1,         sum( if( rr <2, 1, 0 ) ) as da2,         sum( if( rr <1, 1, 0 ) ) as da3 from tv; 	0.00466067043871006
15546625	29933	sorting data from tables according to time with a level of accuracy in datetime	select one.date, one.value value_one, two.value value_two from   one join two   on one.date between two.date and two.date + interval 2 second order by one.date 	7.39237724142921e-05
15560766	28354	generate a script of inserts from existing data with a select clause in sql server	select 'insert into yourtable (id,othercol) values (' + cast(id as varchar) + ',''' + othercol + ''');' from yourtable 	0.0692845020125486
15566609	4947	mysql sum avg of last x number of results where results can be in different columns	select avg(score) avscore from (select debatedate, score       from (select debatedate, hostscore score             from debates             where hostid = 1             union             select debatedate, visitscore score             from debates             where visitid = 1) x       order by debatedate desc       limit 5) y 	0
15572303	17594	oracle correctly getting the month difference	select execution_date,        months_between (trunc(sysdate,'mm'), trunc(execution_date,'mm')) "exec_diff" from v_cert_list   where execution_date < to_date('02/02/2013','dd/mm/yyyy')  order by execution_date desc 	0.0144948680092635
15582528	21892	extract records from mysql based on results from other table	select t2.* from (     select u2 as value from table1      where u1 = :value and status = "confirmed"     union     select u1 as value from table1      where u2 = :value and status = "confirmed" ) as t1, table2 as t2 where t2.u1 = t1.value  or t2.u2 = t1.value order by t2.id 	0
15594565	8812	ltree find parent with most children postgresql	select subpath(path,0,1), count(*)  from test group by subpath(path,0,1) order by count(*) desc limit 1; 	0.00026843173658269
15606841	20120	get auto-increment id after an insert query using mysqli_multi_query	select last_insert_id() 	0.0173862081190178
15611509	16502	sql group by latest entry	select    t1.pcid,   t2.name,   t2.lastonline,   t3.latestpatchinstall from table1 as t1 inner join table2 as t2 on t1.pcid = t2.pcid inner join (   select pcid, max(patchinstall) as latestpatchinstall   from table3   group by pcid ) as t3 on t1.pcid = t3.pcid 	0.00145586020212369
15616913	31641	sql server 2008 mass alter statement for data type	select          cmd = 'alter table [' + c.table_schema + '].[' + c.table_name + '] alter column [' + c.column_name + '] varchar(<yoursize>)'         ,*     from information_schema.columns c     where c.data_type='text' 	0.708264859831264
15637822	13381	select rows where a column contains any result from a subquery	select      t1.*  from mytable t1 join (     select distinct [name] from subtable ) x on t1.mycolumn like '%' + x.[name] + '%' 	0.00100974408522211
15650423	37273	count the number of rows between intervals	select n.hr, n.hr, coalesce(v.cnt, 0) as cnt from (select 0 as hr, -1 as sign union all       select 0, 1 union all       select 1, -1 union all       select 1, 1 union all       . . .       select 23, -1 union all       select 23, 1 union all      ) left outer join      (select hour(time) as hr, sign( minute(time) - 30 ) as sign, count(*) as cnt       from visits        where locationid=3227       group by hour(time), sign( minute(time) - 30 )      ) v      on n.hr = v.hr and n.sign = v.sign order by n.hr, n.hr 	0
15659020	23771	query results from 4 different tables with only 1 known value	select     sem.title,     sub.active,     sub.datetime,     u.firstname,     u.lastname,     unsub.reason   from     seminar sem     inner join  subscription sub  on sub.seminar_id = sem.id     inner join user u on sub.user_id = u.id     left join unsubscription unsub on sub.id = unsub.subscription_id    where      sem.id = your-search-value-here 	0
15662468	33244	count comparison where some characters are numeric	select     sum( isfirstsubcompany ) firstsubcompanyemployeecount     , sum( ismaincompany ) maincompanyemployeecount from     (         select             isfirstsubcompany = case                  when u.num like '%[a-z]%' or ( 1 = isnumeric( u.num ) and convert( int, u.num ) between 55556 and 88888 ) then 1 else 0             end,             ismaincompany = case                 when 1 = isnumeric( u.num ) and convert( int, u.num ) between 00000 and 55555 then 1 else 0             end         from             usertable u         ) q 	0.141148578310618
15667820	13934	select sum of max date	select sites.id, sites.name, sum(data.visits), dp.maxdate from sites inner join      data      on data.profile_id = sites.profile_id inner join      (select profile_id, max(start_date) as maxdate       from data       group by profile_id      ) dp      on data.profile_id = dp.profile_id and data.start_date = dp.maxdate group by sites.profile_id, sites.name, dp.maxdate 	0.00400627940121346
15677599	15993	calculate count in group by sql query	select    p.[id],   sum(case when o.[ownerid] is not null then 1 else 0 end) +   sum(case when o.[id]      is null     then 1 else 0 end) as total from [dbo].[order] o inner join [dbo].[product] p on p.[id] = o.[productid] group by p.[id] 	0.0909551207000641
15678510	8408	count each rows with codeigniter	select dosen_nama, ((select count(*) from topik where dosen_id1=d.dosen_id) +  (select count(*) from topik where dosen_id2=d.dosen_id)) as count from dosen d 	0.000504298632202278
15680890	7649	sql query between time and a distinct column	select vehno, max(ttime) as [ttime], odo from table_1 where vehno = 'abc' and ttime between '2013-02-12 10:30:00' and '2013-02-13 10:30:00' group by vehno, odo order by vehno, odo 	0.00887209869447283
15712442	37263	complex query - mysql (categories x products)	select p.id, p.name, p.img, c.name from categories c inner join      (select p.id, p.name, p.img, p.category_id,              (select count(*) from products p2 where p2.category_id = p.category_id and p2.id <= p.id              ) as seqnum       from products p      ) p      on product.category_id = category.id where seqnum <= 4 	0.0726047972402243
15731999	18443	mysql join with counting results in another table	select * from   md_number_ranges m join (    select md_number_ranges.id         , count(*) as found_rows    from   md_number_list    join   md_number_ranges      on   md_number_list.range_id = md_number_ranges.id    where md_number_list.phone_num_status not in  (2, 0)      and md_number_ranges.reseller_id=1    group by range_id    ) x on x.id=m.id limit 10 offset 0 	0.01184771027256
15736195	17887	mysql limit 1 returns null values	select a.teamcode, a.area,     c.uniqid, concat(c.first_name,  ' ', c.last_name ) as fullname, c.email from teams a    left join (       select max(uniqid) maxuniqid, teamcode       from users        group by teamcode    ) u on a.teamcode = u.teamcode    left join users c on c.teamcode = u.teamcode         and c.uniqid = u.maxuniqid where a.area= 'zf15' 	0.0826784817370046
15745694	11243	mysql date bug because of subtracting one day	select date('2013-04-01') - interval 1 day 	0.00142670504590205
15746469	15384	how to combine two value of two column in a table.	select * from profile where concat(fname,' ',lname) like '%$name%' 	0
15750720	29806	mysql sorting and limit using a certain row and selecting previous and next rows	select * from test  where id in (1,(     select id from test where id > 1 and hops >= (         select hops from test where id = 1         ) order by id limit 1     ), (     select id from test where id < 1 and hops <= (         select hops from test where id = 1         ) order by id desc limit 1 )) 	0
15752167	5318	mysql subquery for max employee hours	select employee_id, sum(timediff(time_off, time_on)) as diff from tbl where year(time_on) = 2013     and month(time_on) = 3 group by employee_id 	0.00540207112934332
15764403	32880	selecting only those numbers that are in array and not in a table	select n.num from (select d1.d*10 + d2.d as n       from (select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all             select 5 union all select 6 union all select 7 union all select 8 union all select 9            ) d1 cross join            (select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all             select 5 union all select 6 union all select 7 union all select 8 union all select 9            ) d2       ) nums left outer join       stands s       on s.stand = nums.n cross join       (select min(stand) as minstand and max(stand) as maxstand from stands) const where s.stand is null and nums.n between minstand and maxstand; 	0
15785925	6105	mysql every derived table must have its own alias	select *  from students as st inner join  (   select  att.roll_no,att.full_name,      sum(att.hasattended= 'p') as dayspresent,      sum(att.hasattended= 'a') as daysabsent,      count(*) as totalclasses   from     attendance as att   group by att.roll_no ) att     on st.roll_no = att.roll_no where st.class = 1  order by  st.roll_no 	0.00314505051968023
15797718	27693	mysql: multiple row compare	select brand, ram, cpu from (    select brand,       max(case when attr='ram' then cast(vals as unsigned) end) as ram,       max(case when attr='cpu' then cast(vals as unsigned) end) as cpu    from attributes    group by brand ) d where ram > 500   and cpu > 1300 	0.00457406814474116
15798262	23934	write a query to select one of rows that have same column data	select  code, name from    (         select  *,                 row_number() over (partition by relatedcode order by code) rn         from    test         ) q where   rn = 1 	0
15804735	8311	search for multiple categories	select * from item where find_in_set('2', idcat) > 0 	0.0875573908495472
15809142	18821	next and previous records in mysql after sorting desc	select cp.*, n.id id_next, n.hops hops_next from (select c.id id_current, c.hops hops_current, p.id id_previous, p.hops hops_previous  from  (select * from users where id = ?) c  left join users p on c.hops < p.hops or (c.id < p.id and c.hops = p.hops)  order by p.hops, p.id limit 1) cp  left join users n         on cp.hops_current > n.hops or (cp.id_current > n.id and cp.hops_current = n.hops) order by n.hops desc, n.id desc limit 1 	0.000421526094343943
15809403	3898	mysql count where and count all	select user_id, @pid:= product_id as product_id, count(user_id),          (select count(*)           from sales           where month(date_added) = month( now() )                and product_id = @pid           group by user_id          ) as total_product_sales from sales  where month(date_added) = month( now() )  group by user_id, product_id; 	0.0217397190141275
15809755	35611	convert different varchar dates to date	select case  when type='ddmmyyyy' then convert(date,stuff(stuff('05032013',3,0,'-'),6,0,'-'),105) when type='mmddyyyy' then cast(substring('03052013',5,4)+'-'+substring('03052013',0,3)+'-'+substring('03052013',3,2) as date) when type='yyyymmdd' then cast(stuff(stuff('20130305',5,0,'-'),8,0,'-') as date) end 	0.000593240857242236
15811900	17945	can i join two tables from different databases?	select * from mysqlsrv.mydb1..mytbl join mssql.mydb2.dbo.myothertbl 	0.00110743966786592
15815961	13791	how to only get non numeric part of column out	select substring(tcode,patindex('%[^0-9]%', tcode),1) from codes where patindex('%[^0-9]%',tcode) > 0 	0
15830070	32970	sql left outer join order by column in left table but preserve all rows	select    t1.id from table1 as t1 left outer join (    select table1_id, sum(column1) sum1, sum(column2) sum2    from table2     group by table1_id ) as t2  on t2.table1_id = t.id         and t1.entry_id  = 2          and t1.parent_id = 0  order by t2.sum1 - t2.sum2; 	0.246086999878368
15857825	36136	how do i count multiple specific values for each item?	select     "description",     sum(       case         when "date" > now() then 0         when "date" > now() - interval 1 month then 1         else 0       end case     ) as "this month",     sum(       case         when "date" > now() - interval 1 month then 0         when "date" > now() - interval 2 month then 1         else 0       end case     ) as "last month",     sum(       case         when "date" > now() - interval 2 month then 0         when "date" > now() - interval 3 month then 1         else 0       end case     ) as "the previous month" from items where "date" > now() - interval 3 month group by "description" 	0
15890367	11067	select from table a which does not exist in table b	select a.* from a left join b on a.band = b.hate where b.hate is null; 	0.00177877026433926
15896095	32865	case compare to number and give out name	select  case when t.cate = 1 then 'stone'              when t.cate = 2 then 'tree'              else null           end as test  from    dbt.tbl t 	0.00805664880024103
15896337	30272	selecting all rows from one table where condition in joined table	select        pro.productname,       pr.productionreportid,       ifnull(pr.qty, 0) qty   from      products pro     left join productionreport pr       on pro.productid = pr.productid      and date(pr.date) = '2013-04-08' 	0
15898913	26544	mysql query to return rows which are not listed in another table	select imei from t1 where imei not in (select imei from t2); 	7.00148249088669e-05
15909250	12007	sql select statement for charge code with max date and second most max date	select t1.mnemonic     , max(t1.std_effective_date) current     , max(t2.std_effective_date) previous from tbl1 t1 left join tb1 t2 on t2.mnemonic = t1.mnemonic                 and t2.std_effective_date < t1.std_effective_date where t1.mnemonic in ('38066','38073','38080') group by t1.mnemonic 	0.000899693119116687
15910549	35747	mysql select to return one of each match	select distinct state from locales where country='us' 	0
15916085	32463	do i have to query twice to get this result?	select  case when invitations.status = 1   then case          when games.status = 1 then 'progress'         when games.status = 2 then 'finished'       end else 'not decided' end as game_status, games.*  from   games         inner join invitations                 on invitations.game_id = games.id                    and invitations.user_id = 1                    and (invitations.status = 0 or                          (invitations.status = 1 and games.status in (1,2))) 	0.087300236153664
15937514	30072	mysql select 3 items from each group and output result set in multiple columns	select   store_id,   max(case when row=1 then product end) product_1,   max(case when row=2 then product end) product_2,   max(case when row=3 then product end) product_3 from (   select     case when @last=store_id then @row:=@row+1 else @row:=1 end row,     store_id,     product,     @last := store_id   from (     select store_id, product     from products     order by store_id, rand()     ) s ) r where   row<=3 group by   store_id 	0
15953280	24628	getting rows from several primary keys sql	select works.id, works.country, works.budget, works.explanation, categories.category, categories_branch.branch from works inner join categories on works.cat_id = categories.id inner join categories_branch on categories_branch.cat_id = categories.id where works.user_id = ".$_session['customer_id']." 	0.000212512571748263
15982838	17548	mysql range date from first date result to x days	select * from orders  where date between {date_added} and date_add({date_added}, interval 5 day) 	0
16002672	29166	disk size of schema postgresql on rails	select_size = "select sum(pg_total_relation_size(table_schema || '.' || table_name)) from information_schema.tables where table_schema = '" + t.schema.to_s + "' group by table_schema" 	0.408866236185209
16024857	11929	query by a long column	select     dbms_lob.instr(clob_contents,'tlp') from     (select          dbms_metadata.get_ddl('view','locked_documents_v', 'schema') clob_contents      from          dual) get_clob 	0.603051429338461
16035994	22327	search number using like from string in mysql	select * from `smartspace_pickups` where find_in_set('37',`cat_id`) limit 0 , 30 	0.0344924337953659
16036673	11151	remove book from search results if it has already been purchased	select * from book where isbn not in (select isbn from books_ordered) 	0.000149691514404782
16045068	11748	calculating relay-race times via a recurrence (in dynamic-sql)	select t.race, t.runner, t.time as starttime,        coalesce(tnext.time, t.finishtime) as endtime,        datediff(sec, t.time, coalesce(tnext.time, t.finishtime)) as seconds from t left outer join      t tnext      on t.race = tnext.race and         t.runner = tnext.runner - 1 	0.0170191357002385
16049635	39303	in mysql, how do i select only every row that has the same value in one column but different ones in another?	select * from mytable where `transactionid` in     (     select `transactionid`           from `mytable`           group by `transactionid`           having count(distinct deliverydate) > 1     ) order by `transactionid` 	0
16051961	3043	select matched pairs from two tables	select  least(a.id, a.matchid) id, greatest(a.id, a.matchid) matchid from    one a         inner join two b             on a.id = b.id and                 a.matchid = b.matchid group   by least(a.id, a.matchid), greatest(a.id, a.matchid) having  count(*) > 1 	7.85744736447599e-05
16052517	36379	data gathering for graph display (sql)	select count(distinct id) as amount from users group by year(create_date),month(create_date),day(create_date) 	0.0134716089687426
16052747	30455	replacing having with where	select * from (   select team, v maxmarks, row_number() over (order by v desc) rnum from(     select team, sum(maths) v     from marks      group by team    )x )xx where rnum=1; 	0.669992025630795
16055336	37667	cast irregular string to integer	select *  from table  where cast(substring(bad_column, 1, charindex('+', bad_column)) as int) = 23; 	0.433350455050613
16055849	17363	how can i print bytea data as a hexadecimal string in postgresql / pgadmin iii?	select encode(bytea_data, 'hex') from my_table; 	0.335951914532003
16067775	24005	nested sql aggregate function query to get lowest paid employees per manager: my query is not working	select empid, salary from employees where salary in (select min(salary) from employees where empid in (select empid from employees where job != 'manager'  group by empid  )  and  job != 'manager' and mgr is not null  group by mgr  ) order by salary asc; 	0.677868618099487
16070117	38629	the column prefix '%s' does not match with a table name or alias name used in the query	select     p.code, p.name as positionname, p.compcommitteemember, count(*) from positions p left join employees e on e.positionid = p.positionid where p.positionid = '{d1b0912d-b1a5-11d4-bbdd-0004acc5b8a7}'  group by p.code, p.name, p.compcommitteemember 	0.598048802254464
16071372	19953	sql select the available rooms by date cheking	select * from rooms left join reservations  on reservations.r_number = rooms.number and reservations.todate > '4/19/2013' and reservations.fromdate < '4/20/2013' where rooms.r_size = 'roomsize'  and reservations.r_number is null 	0.000960504374820127
16081080	4751	sql - same tables different where clause	select distinct       count(distinct t1.p_id) "c1",      count(distinct t2.sa_id) "c2",      count(distinct case when t2.sa_reference like '212%%' then t1.p_id else null end) "c3",      count(distinct case when t2.sa_reference like '212%%' then t2.sa_id else null end) "c4" from capd_section t5,       capd_department t6,      capd_person t1,      capd_studentapplication t2,      capd_module t4,      capd_moduleapplication t3  where (t3.ma_studentapplication(+)=t2.sa_id) and        (t3.ma_module=t4.m_id(+)) and        (t4.m_modulesection=t5.s_id(+)) and        (t4.m_moduledept=t6.d_id(+)) and        (t4.m_reference not like '%%fta%%') and        (t4.m_reference not like '%%he%%') and        (t4.m_reference not like '%%pt%%') and        (t4.m_name not like 'nctj%%') and        (t4.m_reference not like 'me%%') and        (t2.sa_student=t1.p_id)  having (count(distinct t3.ma_id)>0) 	0.0277964739723326
16082718	35872	conversion of 12 hour clock to 24 hour clock in sql server	select parse(' 00:00:12 pm' as time using 'en-us') 	0.000484703762641947
16088051	15279	mysql only select records present in other table	select distinct      lt.id, lt.name from      logging_types as lt     inner join logging as l on lt.id = l.type_id 	0
16089355	31515	order by in t-sql	select  case when @id = 1 then convert(nvarchar(10), [insert_date],101)      else convert(nvarchar(10), [insert_date],103)  end as [insert_date] from dates  order by convert(nvarchar(10), [insert_date],101) desc 	0.448112519884434
16092208	32057	mysql query a subset	select remaining  from quantity_time   order by abs(now() - timestamp(salesdate,salestime)) desc limit 1 	0.17371597549817
16093371	17914	addition of two queries sql	select sum(sm) as total_sum from (   select sum(datalength(money)) / 1048576.0 as sm    from money   union all   select sum(datalength(cc)) / 1048576.0    from cc ) t 	0.0720594126354802
16121838	32567	getting data from table where one field is maximum in one query	select * from data order by timestamp desc limit 1 	0
16141923	7318	import only sequences from an oracle exp dump	select dbms_metadata.get_ddl('sequence', u.sequence_name, decode(u.sequence_owner,'sys','',sequence_owner)) ddl      from all_sequences u where sequence_owner = 'soe' order by sequence_owner, sequence_name; 	0.0505239291542832
16148210	13888	how to map mysql result to replace resultant values with correspondent ones	select (case when status = 0 then 'disabled'              when status = 1 then 'enabled'         end) from . . . 	0.0175079082666341
16151493	22419	update foreign key table reference after bulk delete/insert?	select primarykeyfield as rowid, childkeyfield as oldchildid, newid() as newchildid into #updatetable from tablea where someconditiontoselectthechildrecords update tablea set tablea.childkeyfield = #updatetable.newchildid from tablea     inner join #updatetable on tablea.primarykeyfield = #updatetable.rowid update tableb set tableb.childkeyfield = #updatetable.newchildid from tableb     inner join #updatetable on tableb.childkeyfield = #updatetable.oldchildid 	0.000726402883902405
16177493	6455	mysql select 5 rows where sum of one combined column best matches a determined value	select * from t as t1, t as t2, t as t3, t as t4, t as t5 order by abs(t1.val + t2.val + t3.val + t4.val + t5.val - 150) limit 1 	0
16185584	7963	filter table data using select sql statment	select  id , firstname , middlename , lastname     from studentsinformation where id = @id         or firstname like '%' + @firstname + '%'     or middlename like '%' + @middlename + '%'     or lastname like '%' + @lastname + '%' 	0.135914555700798
16187821	12929	how to generate consecutive records with a given number?	select level  from dual  connect by level <= 100 	0
16194044	34980	hypothetical: storing date-time data with varying specificity in sql server for .net mvc app	select case when month is null then 'yearonly'             when day is null then 'yearmonth'             else 'fulldate'        end as specialdatetype   from dbo.yourtable; 	0.798561145244412
16197939	8436	sql using same codes table for two different columns	select name from codes c inner join foo f on c.code = f.code1 or c.code = f.code2 	9.8108655804165e-05
16208178	394	sql query group by	select * from(   select a.firstname, a.lastname, b.studentid, b.courseid, count(*) over (partition by b.courseid) cnum   from student a inner join enrolled b on a.sid=b.studentid   ) x where cnum=2 	0.576087973847006
16211205	19988	sql server identity related error	select * into dbo.stagingtable from abc where 1=2     go     bulk      insert stagingtable     from 'f:\test.csv'     with     (         fieldterminator = ',',         rowterminator = '\n'     )     go     set identity_insert abc on go     insert into abc (column1,column2,etc)      select * from stagingtable 	0.692962062241965
16211930	9897	how to order by date when the column is not date formatted?	select max(convert(datetime, datecolumn, 109)) 	0.00437484728148876
16218179	25356	sql server 2008 column to row data	select acctid,yr,cast(right(pd,2) as int) as pd, amt from #cols unpivot (amt for pd in ([pd01],[pd02],[pd03],..., [pd13])) unp 	0.0226787945946171
16218974	5260	t-sql : get current + previous years from date table	select * from table where datepart(year, date) <= datepart(year, getdate()) 	0
16223623	20593	query to show all data unless related to user	select b.item, b.item_id, a.review_id, a.review, c.category, u.username, c.cat_id  from reviews a inner join items b      on a.item_id = b.item_id inner join master_cat c      on c.cat_id = b.cat_id inner join users u      on u.user_id = a.user_id where not exists(select 1 from profile_follow where user_id = '{$user_id}' and follow_id = a.user_id) order by a.review_id desc; 	0.000344053819156889
16226088	2187	select from table a but exclude where a match exists in table b	select distinct s.emailaddress    , 'gopro' as campaignname   , sl.senddate from subscribers s  left join sendlog sl    on s.emailaddress = sl.emailaddress   and campaignname = 'gopro' where s.entitlement = 'poweruser'  and s.subscribepreference = 1 and sl.emailaddress is null 	0
16230533	3475	select top category from subcategory id	select parent.categoryid from categorytable as parent join categorytable as child on child.parentid = parent.categoryid join contenttable           on child.categoryid = contenttable.categoryid 	0.00012085843234457
16233650	34647	unioning and joining in 1 query?	select x.a, x.b, x.c, d from (   select a, b, c from table1   union all   select a, b, c from table2 ) x left join table3 on ( table3.a = x.a ) 	0.125508976880334
16238691	29488	show string constant for a group having multiple values	select attrname,        case when count(*) = 1 then min(attrval) else 'multiple values' end  from myview group by attrname 	0.00281097954015097
16240612	15457	combining two complex sql queries	select c.*,         if(hour(timediff(now(), c.time)) >=1, 1, 0) as latestolderthananhour,        min(h.time) as earliesttime,         (abs(timestampdiff(hour,now(),min(time)))/count(*)*100) as percentage from current c join historical h on c.id = h.id where c.location like "mylocation" group by c.id 	0.49801880111798
16253174	24455	swap columns value in output based on certain condition using sql server	select (case when symbol='<' then [to]  else [from] end)as [from],(case when symbol='<' then [from]  else [to] end)as [to] from temp 	0
16254066	2147	query with subquery not returning all results	select x.*    from my_table x    join       ( select id           from my_table          where keyt = 21          order             by rand() limit 1      ) y      on y.id = x.id; 	0.664724912416701
16257994	5799	sql query select from three tables	select      posts.id as post_id,     categories.id as category_id,      title, contents,      posts.date_posted,      categories.name,      comments.id as comment_id from posts p, categories c, comments co left join (categories, comments) on categories.id = posts.cat_id and posts.id = comments.post_id where p.cat_id = c.id  and (co.post_id is null or co.post_id = p.id) and posts.id = 28 	0.022881921005335
16258849	26659	is it possible to use these 2 mysql queries in only one query?	select *, count(*) from track t where t.referid='".$member."' group by t.referer  order by t.id desc limit 0,15 join (    select id, country, num, num*100/total pct     from (select id,country, count(*) as num     from track group by country     order by num desc limit 3) x     join (select count(*) total from track) y ) tc on t.id = tc.id 	0.100710383538415
16262455	10065	sql related fields and duplicates	select * from logs l join (   select prod, amt   from logs   where time between '02:00' and '06:00'   group by prod, amt   having count(*)>1 ) tmp on tmp.prod=l.prod and tmp.amt=l.amt where time between '02:00' and '06:00' 	0.0202349768678933
16284946	20604	select distinct and get count	select  awardreference.ownerid ,         count(*) as count from    awardreference where   awardreference.ownertype = 'song' group by awardreference.ownerid 	0.00607432720636666
16287542	25413	sql query where one item is always placed last	select * from    table1  order by   case when data = 'bear' then 1 else 0 end,   sort_id 	0.000210377347449893
16288346	8500	compare rows in sql query	select id, checkin, checkout from (select t.*, max(checkout) over (partition by id) as maxco       from t      ) t where maxco <= trunc(sysdate) 	0.0171424670019825
16300815	10292	calculating the average time between orders for each customer	select cust_id , avg(orderdate - lag_orderdate) as avg_time_between_orders from (     select cust_id , orderdate , lag(orderdate) over (partition by cust_id) as lag_orderdate     from  orders ) 	0
16303928	31859	query to change/update existing integer value to character value in a table in sql server	select char(col1+65) as col1 from tbl_test 	0.00149496701322927
16316215	9252	add mysql cumulative frequency field using any method	select d1.date_tr, sum(d1.sales) as daily_sales, (select sum(d2.sales)  from dailyactivity d2  where d2.date_tr <= d1.date_tr) as cumulative_sum from dailyactivity d1 group by d1.date_tr order by d1.date_tr asc 	0.0122111790047572
16318346	34054	how do i build a sql statement that selects multiple rows and sums the amount?	select ppolno, sum(pprmpd) pprmpd from pfntlpymth group by ppolno 	0.00175696297448614
16331216	34632	how to search min value from four other different fields in mysql query?	select     package_id,     least(price, price_double, price_triple, price_quad) as price from package; 	0
16336348	9314	select records where rows have difference on a specific column	select customer_id, count(distinct tariff) as tariffs  from campaign_data  group by customer_id  having tariffs > 1 	0
16356875	37966	combining sql records that have the same the same value in a given field	select  coursetitle ,       entrymonth ,       stuff((         select  ', ' + cast(entryyear as varchar)         from    table1 t2         where   t1.coursetitle = t2.coursetitle                 and t1.entrymonth = t2.entrymonth         for xml path('')         ), 1, 2, '') as years from    table1 t1 group by         coursetitle ,       entrymonth 	0
16359678	33126	sql server database diagram show relationships	select    [foreignkey] = f.name , [tablename] = object_name(f.parent_object_id), col_name(fc.parent_object_id,fc.parent_column_id) , [referencetablename] = object_name (f.referenced_object_id) , referencecolumnname = col_name(fc.referenced_object_id, fc.referenced_column_id) from  sys.foreign_keys as f inner join sys.foreign_key_columns as fc on f.object_id = fc.constraint_object_id 	0.281727287608275
16361705	24731	format date in mysql query that uses cast	select date_format(exp_channel_titles.edit_date, '%d/%m/%y %k:%i:%s') 	0.383401653741074
16366399	6174	mysql query to convert a table into distinct column and other column count array?	select   week,   sum(result='good') as good_result,   sum(result='bad') as bad_result,   sum(result='worst') as worst_result,   count(*) as total from yourtable group by   week 	0
16384461	26333	displaying two foreign keys linked with one primary key	select     t.id,     s1.name start,     s2.name end from trip t     join stop s1         t.start = s1.id     join stop s2         t.end = s2.id 	0
16393089	23079	sql redundant results	select firstname, lastname, email from consultants, skills where skills.expertiseid = '3' and  ( consultants.state = 'nj' or consultants.state = 'ny' ); group by firstname, lastname, email 	0.577919071581624
16394494	30715	how to display this sql query as one table	select players.name from players inner join teams on players.team = teams.name where teams.staysat = 'ambassador' and teams.checkin is not null; union select fans.name from fans where fans.staysat = 'ambassador' and teams.checkin is not null; 	0.0112198428464789
16398647	2346	oracle sql 3 tables with count condition and equal condition	select distinct s.address     from shop s      join visit v on s.shopid = v.shopid      join customer c on v.customerid = c.customerid      where c.cname = 'john'      group by      s.address     , c.customerid      having count(*) > 1 	0.0987312468914279
16400172	29403	selecting dates when column value changes	select b.*   from      ( select x.*       , count(*) rank   from campaign_charges x   join campaign_charges y     on y.campaign_id = x.campaign_id    and y.id <= x.id  group     by x.campaign_id      , x.id       ) a join     ( select x.*       , count(*) rank   from campaign_charges x   join campaign_charges y     on y.campaign_id = x.campaign_id    and y.id <= x.id  group     by x.campaign_id      , x.id       ) b      on b.campaign_id = a.campaign_id and b.rank = a.rank+1    and a.charges <> b.charges; 	0.000504655174385126
16403500	33158	mysql how to select items from table a where all corresponding items in table b satisfy condition	select * from a  where m_active='n' and not exists (     select * from b      where b.m_id=a.m_id     and b.v_active<>'n' ); 	0
16416384	28064	query mysql group by and having	select finisher.studentid from (     select distinct studentid     from table1 t1     join table2 t2 on t2.subjectid = t1.subjectid     where t1.present = 'yes' and t1.type1 = 1     group by t1.studentid, t2.subjectid     having count(*) / t2.number2 >= 0.75 ) finisher join (     select distinct t1.studentid     from table1 t1     left join     (          select distinct studentid          from table1          where type = 3 and present = 'no'     ) missed on missed.studentid = t1.studentid     where t1.type = 3     and missed.studentid is null ) notmissed on finisher.studentid = notmissed.studentid 	0.605325994471543
16417266	5956	class wise, student name who has max aggregate of marks	select  classstudentsum.* from    (         select  class         ,       student         ,       sum(marks) as summarks         from    yourtable         group by                 class         ,       student         ) as classstudentsum join    (         select  class         ,       max(summarks) as maxsummarks         from    (                 select  class                 ,       student                 ,       sum(marks) as summarks                 from    yourtable                 group by                         class                 ,       student                 ) classstudentsum2         group by                 class         ) maxperclass on      maxperclass.class = classstudentsum.class         and maxperclass.maxsummarks = classstudentsum.summarks 	0.000909247887582174
16417943	13235	sql query across three tables	select top 1 a.salary, b.college, c.playerid  from salaries as a inner join directory as b on a.playerid=b.playerid inner join playersschools as c on b.playerid=c.playerid sort by a.salary desc 	0.0941236909490619
16423246	25041	including posts that users have commented on	select u.user_fullname,   round(avg(p.total_points),2) avgpoints,  (select round(avg(total_points),2) from cl_posts p2 join cl_comments c2 on c2.post_id = p2.post_id where c2.user_identity_id = u.user_identity_id) as avgpoints2 from cl_user_identities u join cl_posts p on p.user_identity_id = u.user_identity_id group by u.user_identity_id 	8.48434244721249e-05
16427282	16200	combining two sql queries	select e.id, e.version, e.name, i.name as implementationid, e.manageddatarepoid, e.description, e.parentid from implementation i      join entity e          on e.implementationid = i.id 	0.081417787109067
16437092	25837	selecting entries from a table by checking condition on another table	select t1.serviceid from table1 t1 inner join table2 t2 on t1.id = t2.id where t2.value is not null 	0
16438665	28618	joining two select statement in sql	select      coalesce(a.id,b.id),     coalesce(a.item,b.item),      yr1qty,      yr1amt,      yr2qty,      yr2amt from     (     select a.id, b.item, a.sum(qty) as 'yr1qty', a.yr1amt from table a     left join table b on a.code = b.code     where date between '04/01/2012' and '04/07/2012'     group by a.id, b. item) as a     full outer join     (     select a.id, b.item, a.sum(qty) as 'yr2qty', a.yr2amt from table a     left join table b on a.code = b.code     where date between '04/01/2013' and '04/07/2013'     group by a.id, b. item     ) as b on a.id = b.id 	0.111125523307786
16447516	27150	unpivot a columns to generate rows	select val from   (     select col1 = '1', col2 = '2', col3 = '3' ) a unpivot  (    var for col in (col1, col2, col3) ) as unpvt 	0.00220498358829498
16450114	17845	joining three tables in mysql database	select  result.date, result.team, result.team_score       , lineup.player1, p1.weight       , lineup.player2, p2.weight       , lineup.player3, p3.weight       , lineup.player4, p4.weight       , lineup.player5, p5.weight from result, players p1, players p2, players p3, players p4, players p5, lineup  where result.date = lineup.date and p1.playerid = lineup.playe1 and p2.playerid = lineup.playe2 and p3.playerid = lineup.playe3 and p4.playerid = lineup.playe4 and p5.playerid = lineup.playe5; 	0.0325166504492404
16450779	26352	another approach to percentiles?	select pcs.percentile, min(case when cumjobs >= totjobs * percentile then duration end) from (select batch_id, job_count,              sum(job_count) over (order by duration) as cumjobs,              sum(job_count) over () as totjobs,              duration       from test_data      ) t cross join      (select 0.25 as percentile from dual union all       select 0.5 from dual union all       select 0.75 from dual      ) pcs group by pcs.percentile; 	0.060630200337806
16456905	40425	complete tables and its columns of specific db, how to get in sql server 2008 r2	select table_schema, table_name, column_name, ordinal_position,    column_default, data_type, character_maximum_length,    numeric_precision, numeric_precision_radix, numeric_scale,    datetime_precision from information_schema.columns order by table_name 	0.000548487722557764
16457118	19999	sqlite: select rows with time in range	select * from table where time(time) between "14:30:00" and "16:30:00"; 	0.00146771172546765
16467641	9649	subtracting in sql server	select (s25)-(c25) as [25_score] from table_name 	0.158856983389237
16467936	29724	mysql issue howto count result in master table not including all rows from a detail table "labels" used in a join	select     count( m.id ) as andtall,   sum( m.cost ) as cost from  master m  join (      select        masterid     from        labels l      where       l.name in ('label1', 'label2')      group by master_id ) l on l.masterid = m.id 	0.000173183558379511
16477704	1537	pivoting data in sql server 2008	select [accountmanager], [clientdeliverydate], [localcontactemail],[projectdeveloper] ,[servicetype] from (     select columnname, testtype, score     from      (         select columnname, minid, maxid  from table_name     ) pivotdata     unpivot     (         score for testtype in (minid, maxid)     ) as initialunpivot ) as pivotsource pivot  ( min(score) for columnname in ([accountmanager], [clientdeliverydate], [localcontactemail],[projectdeveloper] ,[servicetype]) ) as pivottable order by [accountmanager] desc 	0.441300323406342
16478331	24558	sql server 2005 - 3 table conundrum	select clid from (select distinct t1.bkid, t2.clid from clients t1, banks t2      where t2.bkid not in       (select  bkid from  exceptions t3 where t1.clid = t3.clid ) ) as t1                            where clid  not in (select clid from exceptions where bkid = %yourspecific bankid%)   group by clid   having count(*) <= 2 	0.77087830230383
16487522	27921	counting items on tables	select m.itemid,         ifnull(ccount,0) as rental_count,        ifnull(ocount,0) as outlet_count from machine m left join (select itemid,              count(*) as ccount              from clientmachine               where acquisitiontype = 'rental' group by itemid) a1 on (a1.itemid=m.itemid) left join (select itemid,              count(*) as ocount              from outletmachine group by itemid) a2 on (a2.itemid=m.itemid) 	0.00180777395805914
16508205	9820	how do i split the street values into atomic in pl/sql?	select    addr,    regexp_substr(addr, '^(.*?)\s\d+$', 1, 1, '', 1) street_number,    regexp_substr(addr, '^.*?\s+(\d*?)\s*$', 1, 1, '', 1) street_name from t1    where     regexp_like(addr, '\d.*\s(street|road|rd|ave|avenue|hwy)\s*$', 'i') 	0.0013082108744616
16508875	3156	mysql query to find related posts by tag and sort by popular?	select at.article_id,count(*) as q  from article_tags at inner join article_info ai on at.article_id = ai.article_id where at.id_tag in (     select id_tag      from article_tags      where article_id=41 )  and at.article_id!=41  group by at.article_id  order by q desc, ai.article_view desc 	8.65980194302502e-05
16513226	35561	fallback condition in a mysql select statement	select    vp1.*  from    validproduct vp1  inner join   (     select        productid, min(sizeid) as minsize      from        validproduct      where        visible = true and       typeid = 2     group by     productid   ) as vp2 on    vp1.productid = vp2.productid and    vp1.sizeid = vp2.minsize and    vp1.visible = true and   vp1.typeid = 2 group by    vp1.productid; 	0.726143924155839
16514024	33562	joining multiple sql queries to display online friends list?	select  f.sender as friend1,     f.recipient as friend2,     u1.loginip ip1,     u2.loginip ip2 from subscribers f inner join users u1 on u1.id = f.sender inner join users u2 on u2.id = f.recipient inner join online o1 on o1.ip = u1.loginip inner join online o2 on o2.ip = u2.loginip where      f.sender = 5 or      f.recipient = 5; 	0.00029511155628091
16527357	35401	how do i match against multiple conditions on a table join?	select u.*, a.id, b.id, a.name, b.name  from users u join attributes a on a.user_id = u.user_id and a.name = 'bla' join attributes b on u.user_id = b.user_id and b.name = 'blub' 	0.0189246888882805
16537459	5703	updating timestamp column by adding value from other column	select      start,       start + game_duration * interval '1 seconds' as finish_time   from "game_played" where id = 123; 	0
16538970	16479	sql union or other table join	select user2 from members where user1 = 'foo@a.com' union select user1 from members where user2 = 'foo@a.com' 	0.180430113698368
16541866	5280	create a rank column on mysql query	select *, @rownum := @rownum + 1 from ( select (display_name) 'author',     ifnull(round(sum(balance.meta_value),2),2) 'balance',     ifnull(round((((sum(balance.meta_value+bet.meta_value)-sum(bet.meta_value))/sum(bet.meta_value))*100),2),2) 'yield %' from wp_posts p join wp_users u      on p.post_author = u.id left join wp_postmeta bet      on p.id = bet.post_id and bet.meta_key = 'bet' left join wp_postmeta balance      on p.id = balance.post_id and balance.meta_key = 'balance' where p.post_status = 'publish' group by u.id order by balance desc )x, (select @rownum := 0) r 	0.0558625652070987
16546386	33022	oracle combine two rows into one	select some_date ,      some_id ,      some_name ,      some_number ,      max(paid) paid ,      max(amount) amount ,      max(etc) etc from   some_table group by some_date ,      some_id ,      some_name ,      some_number 	0.000100996846396092
16546724	30906	how to loop through stored procedure recordset?	select     nh.hireid,     isnull(1e0 *           count(case when hireresponse in (0,1) then hr.hireid end) /            nullif(count(hr.hireid), 0)        , 0) as percentage from     newhire nh     left join     hire_response hr on nh.hireid = hr.hireid group by     nh.hireid 	0.408492435130236
16550243	29251	how to order by multiple fields in mysql?	select brand, type, transmission       from tablename  order by   case brand   when 'toyota' then 1   when 'honda' then 2   when 'ford' then 3  end asc,  case type   when 'suv' then 1   when 'sedan' then 2   when 'coupe' then 3  end asc,  case transmission   when 'manual' then 1   when 'automatic' then 2   when 'cvt' then 3  end asc 	0.047766835121019
16580757	36406	query to check detail from table if found then yes else no	select       u_m.*,concat(usr.fname,' ',usr.lname) as name,       u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,       u_m_u.author,u_m_u.adddate,if(likes.liked_by is null,'no','yes') as likees from user_message_users as u_m_u       left join user_messages as u_m         on u_m.messageid = u_m_u.messageid        left join smsusers as usr         on u_m_u.sent_by=usr.id        left join likes          on u_m.messageid=likes.element_id  and likes.liked_by='1' group by u_m_u.messageid,u_m_u.sent_to order by u_m_u.adddate desc; 	0.0006803640165345
16589239	22250	sql select only the rows not containing id used in related table	select products.id      from products      left join sale_products on sale_products.product_id = products.id      where sales_products.product_id is null     group by products.id 	0
16590590	23727	union and intersection of data	select u.id, u.name from user u  inner join user_group g    on u.id = g.user_id  where ug.group_type_id in (1,3)  group by u.id, u.name  having count(distinct ug.group_type_id) = 2 	0.0613449822121469
16602343	31358	select post with the term id	select      p.id from      wp_posts p  left join wp_term_relationships t on (p.id = t.object_id) where      exists (         select tt.term_taxonomy_id from wp_term_taxonomy tt         where tt.term_taxonomy_id = t.term_taxonomy_id          and tt.term_id in(86,39)     ) group by p.id having count(p.id) = 2 	0.00603361749492701
16607230	39321	mysql - php - need to get only the latest record from a self referencing data	select s.* from   selectioncommunication s natural join (   select   parentmessageid, max(datetimecreated) datetimecreated   from     selectioncommunication   where    msgfrom = 7 or msgto = 7   group by parentmessageid ) t where  s.msgfrom = 7 or s.msgto = 7 	0
16616478	25567	how to select only double matched records from a table?	select   ip, group_concat(distinct user) as users from     my_table group by ip having   count(distinct user) > 1 	0
16640252	19781	mysql count row values where column = value	select     name,     sum(votes) as total_votes from mytable group by 1 order by 2 desc 	0.00030822805521814
16643037	25474	how to join two table values in sql	select sc.name  from        states as s2  left join        (select s.statename as name,                 s.stateid            from   states s         union all         select c.cityname as name,                c.stateid            from   city c) as sc  on sc.stateid = s2.stateid 	0.00583015855360506
16654423	15654	displaying results from different tables in mysql	select distinct    theatre.county as countyfromtheatre,   city.county as countyfromcity, from show inner join theatre on theatre.name=`show`.venue inner join city on city.name=thetare.city where `show`.artist='one direction' and city.country='uk' 	0.00130537970021185
16654633	13869	find a whole sentence by sql contains command	select * from files where contains(file_stream,'"sql server"') 	0.0718231093896873
16658123	39602	counting combinations of rows/columns across one table	select * from filteredcontact  pivot ( count(p_id)         for datatel_prospectstatusname in ([accepted], [enrolled])       ) as p 	5.09976486946663e-05
16670897	7701	mysql[fulltext search]- show search term used to get that particular result	select     tmp1.msg,     tmp2.tag_name from (     select          convert(name using utf8) as msg      from          `articles`      where          match(`name`) against ('term1 term2' in boolean mode) ) as tmp1 inner join (     select convert('term1' using utf8) as tag_name     union     select convert('term2' using utf8) as tag_name       ) as tmp2     on tmp1.msg like concat('%',tmp2.tag_name,'%') 	0.00290469094965752
16673807	29916	how make query with unique?	select distinct top 20      f.name as f_name from ... 	0.215332348578097
16676522	25882	getting a count of distinct counts in mysql	select team_count, count(*) from (select count(*) team_count from players group by team_id) sq group by team_count 	0.00420980614390747
16680549	26717	find all "null" values using xquery	select * from yourtable  where attributelist.exist('/attributelist/nodea/node()') = 0 	0.0024358359207401
16683758	30303	how to create a table from select query result in sql server 2008	select * into new_table  from  old_table 	0.0234969106140299
16691408	25346	select max value among rows where another value is the same	select city, max(discount) as maxdiscount  from customer, sales, goods where customer.cid = sales.cid   and goods.gid = sales.gid group by city 	0
16698248	25953	mysql update date year	select date_add(t_date - interval 1 year), t_date from your tablename where year(t_date) =2013 update yourtablename set t_date= date_add(t_date-interval 1) year where year(t_date) = 2013 	0.00886843734901262
16699983	32455	finding a way to join on the latest range of dates?	select isbd.itemid, isbd.sales, isbd.date, spic.cost from itemsalesbydate isbd left join  saleperiodsanditemcosts spic   on spic.itemid = isbc.itemid    and spic.enddate =     (select max(spic2.enddate)      from saleperiodsanditemcosts spic2      where spic2.itemid = isbd.itemid) 	0
16701180	16464	oracle using regexp_substr to return values within brackets	select regexp_replace(    'projs["aa",zzzz[parameter["one",1]],projection["transverse"],unit["two",2]]',    '^.*projection\[(.+?)\].*$', '\1' ) from dual 	0.137202265630723
16706510	33395	mysql how many columns table have	select count(*) from information_schema.columns where table_name = 'darbuotojai' 	0.00220080191219944
16716447	22959	count if a user has reached the borrwing limit	select col1.id, col1.holder, col2.borrowmax, count(lend.borrowedid) as `count` from collection_db col1   inner join collection_db col2   on col1.holder = col2.id     inner join lendings lend     on col1.holder = lend.holder where col1.id = $id and col2.category = 10 and lend.memid = $medid 	0.00248239286221434
16720236	9927	get direct descendants count with hierarchyid	select  a.empid, a.empname, a.position, count(b.empid) as directdescendantscount from    employee as a          left outer join employee as b             on a.position = b.position.getancestor(1) group by a.empid, a.empname, a.position 	0.0161232450684301
16729335	2681	string delimiting in sql server taking input from a table	select *  from dbo.mytable t outer apply (     select *      from dbo.fnsplit(t.mycolumn) y ) y 	0.0269946087154103
16735607	38934	how do i troubleshoot a query that executes indefinitely?	select         db_name(l.resource_database_id)        ,object_name(p.object_id)               ,* from sys.dm_tran_locks l left join sys.partitions p     on p.hobt_id = l.resource_associated_entity_id where 1=1     and object_name(p.object_id) is not null  	0.486764953697546
16743751	19883	how to aggregate counts across two sql tables?	select mt.medicinetypeid, mt.medicinetypename, count(m.medicineid) as medicinecount from medicinetype inner join msmedicine m on mt.medicinetypeid = m.medicinetypeid group by mt.medicinetypeid, mt.medicinetypename 	0.0112519689797156
16747152	18645	join tables according to a column of the table	select `tbl_importantdates`.*, case when importantdatetype = 1 then tbl_elecdivision.elecdivname, case when importantdatetype = 2 then tbl_villages. villagename else 'nothing' end name 	0.000184480294558569
16770899	12074	how to get one distinct listofdate column from two different tables columns sql server	select idemp_lv, leavedate as listofdates  from leaves  where approvalstatus='approved' and leavedate >='20130302' and  leavedate <'20130501'  union  select idemp_at, absentdate  as listofdates  from attendanceatd  where  absentdate >='20130302' and  absentdate <'20130501' 	0
16787309	21252	unix_timestamp date and time difference	select receivedtime,         requesttime,        case when timestampdiff(second, requesttime, receivedtime) < time_to_sec(sla)              then 'meet' else 'don\'t meet' end sla   from table1 	0.00737913767411387
16796350	39999	to_char and to_date are returning different output	select sysdate from dual 	0.785971460608346
16819144	18250	how can i select a row that may contain swapped fields?	select * from t where submitted = 1 and 2 in (user_1, user_2) 	0.00246083070295572
16819662	5261	creating a table with one of the column values from an expression	select orderid,        round(sum(nz([quantity]*[unitprice]*(1-[discount])*100)/100)+             [rushcharge],2) as totalcost from  from [order details] group by orderid 	0.000276902374117622
16822754	833	using data from a current query	select a.id, b.color, c.yourcol from table1 a inner join table2 b   on a.id = b.id inner join table3 c   on a.id = c.id   and b.color = c.color 	0.00135912421517786
16835533	16578	is there a way to filter by a calculated value without wrapping it in another select?	select id, name, sum(qty * price) as value from docs having value like '%something%' or name like '%something%' 	0.00446054345722949
16840971	29138	find the max value of a column, then group by another column in same table	select document.*, doctype.*  from document    inner join doctype         on document.iddoctypes = doctype.iddoctypes where document.revision = (     select max(d1.revision)     from document d1      where document.linkid = d1.linkid )   order by document.doccreation desc 	0
16842556	16694	joining two tables that has no columns in common	select columns from   table1         inner join table2           on right(table1.columna, 50) = right(table2.columnb, 50) 	0
16844581	548	sql trying to concatenate 'attn" on a field when field is not null	select  'attncontact' = case when bilcontact is not null and bilcontact != '' then 'attn: ' + bilcontact end  from packinglist select  case when bilcontact is not null and bilcontact != '' then 'attn: ' + bilcontact end as attncontact from packinglist 	0.012368258399587
16845196	38706	group by with sum total quantity sold for each product for each customer	select a.agent_name, b.order_id,      b.orderline_productname, sum(b.orderline_quantitysold) from agents a  left join orderlines b on a.agent_id = b.agent_id group by a.agent_name, b.orderline_productname, b.order_id 	0
16859127	19663	return products where there was no sales for month	select  dp.* from    dbo.dimproduct as dp         left join dbo.factsales as fs              on  fs.productid = dp.productid and                 datename(month, fs.orderdate) = 'july' and                 year(fs.orderdate) = 2004 where   fs.productid is null 	0.000206000252843249
16862685	8170	mysql how to covert table from relationship from onetoone to onetomany merging its columns in to rows	select id, mobile1 as mobile from yt union all select id, mobile2 as mobile from yt union all select id, mobile3 as mobile from yt; 	0
16870865	8746	top 3 scores - mysql	select name, score from scores join (select distinct score score3       from scores       order by score desc       limit 2, 1) x on score >= score3 order by score desc 	0.05853234529979
16882294	29662	mysql: like (subquery) returning many rows	select message  from systemeventsr s join users u   on s.message like concat('%',u.username,'%') 	0.532647387691616
16890660	995	php - mysql different query	select id from category where id not in (select distinct parent_of from category) order by id desc 	0.116200082436564
16936611	35632	getting newer and older posts from mysql, but at least a certain number	select * from (select     listed,data,@r2 := @r2 + 1 as num from    jokes,   (select @r2:=0) as e) t where find_in_set(num,(select found from (select      listed,`data`,@rn := @rn + 1 as number,     if(listed = '2013-01-07',#pass your date here         if(@rn = 1,concat(2,',',3),             if(@rn = (select count(*) from jokes),concat(@rn-1,',',@rn-2),concat(@rn-1,',',@rn+1)))    ,-1)          as `found` from jokes,(select @rn := 0 ) r order by listed ) as k  where `found` != -1))>0 	0
16938580	19532	oracle check across multiple columns and return the first not 0.00	select o.id, coalesce(nullif(o.value_one, 0.0),                        nullif(o.value_two, 0.0),                        nullif(o.value_three, 0.0)) as new_value  from foo 	0.000240015809944883
16946784	19479	average of latest n records per group	select user_id, avg(points) as pts  from (select user_id, if(@uid = (@uid := user_id), @auto:=@auto + 1, @auto := 1) autono, points       from players, (select @uid := 0, @auto:= 1) a        where points != 0        order by user_id, match_id desc      ) as a  where autono <= 30 group by user_id; 	0
16947762	15943	exclude sql query results - single table	select    order_number,    order_line,    package from     atable where  not exists (select 1                      from atable as b                     where atable.order_number = b.order_number                           and atable.order_line = b.order_line                           and b.package != 1) group by order_number,      order_line,      package 	0.0103741965139556
16950553	27455	sql date number	select username,        select min(date) over (partition by username) as firstdate,        date,        row_number() over (partition by username order by date) as date_sequence from data as outer; 	0.013218550679795
16955216	29481	sql database date column is comparing with current date	select          id, eve_name, eve_date, eve_place,eve_desc      from          eventdetails      where           eve_date >= getdate() 	0.000174423700431852
16962713	41114	i have a sql query where i have use a list of id inside in and i want my result sorted as per my list	select * from `wp_patient_bill` where `bill_code` !='' and `is_billed` = 'y' and `charged` = 'n' and `id` in (97,419,631,632,633,422,635,421,35,799,60,423) order by field(`id`,97,419,631,632,633,422,635,421,35,799,60,423) 	0.000101280311613983
16974621	6684	how to get multiple items in one line in mysql?	select s.name as employee, group_concat( e.name )  from employees s left outer join employees e on s.id = e.manager_id group by s.id 	7.16516626364456e-05
16989344	39667	mysql - extract part of string before and after substr	select    substring_index(substring(column_name,5), '?', 1) as part2  from table_name 	0.0192747322759532
16994092	39879	sql questions for selecting correct data	select pc.product_id, kc.color_id, c.color_name  from kit_color as kc left join color as c on kc.color_id = c.color_id left join product_color as pc on pc.color_id = c.color_id where kc.id = %s 	0.111364446279792
17012769	35417	how to get a ranking result for special record in mysql	select id, name, @rn := @rn+1 as `rank` from `users` cross join (select @rn := 0) const order by points desc 	0.00312368948429598
17034960	11722	retrieving the most recent entry per user	select my_table.* from my_table natural join (   select   user_id, max(created_at) created_at   from     my_table   group by user_id ) t 	0
17044547	26335	convert years and weeks to date in sql msaccess	select fieldname, dateadd("ww",cdbl(mid([fieldname],6,2))-1,dateserial(mid([fieldname],2,2),1,1)) as convdate from tablename 	0.00389488045408493
17047302	36398	mysql select top 10% of users	select user_id, date, total_time from (   select user_id, @rownum:=@rownum+1 as rownum    from table_user , (select @rownum:=0) r   where date = current_date    order by total_time desc ) temp  where rownum < (select count(*) from table_user where date = current_date) / 10 	0.000279555757965101
17059188	174	how to join tables using a range of dates without having procedures	select a.num1       ,a.num2       ,nvl(          (select distinct                  first_value(b.status)                  over (order by b.date desc)           from   b           where  b.num1 = a.num1           and    b.num2 = a.num2           and    b.date <= a.date          ),'new') as status       ,a.date from a; 	0.00129220506631732
17060007	23395	select column data between () parantheses	select  * ,     reverse(t.[column]) as reversed ,     case when t.[column] like '%(%'               and t.[column] like '%)%'          then reverse(substring(reverse(t.[column]),                                 charindex(')', reverse(t.[column])) + 1,                                 charindex('(', reverse(t.[column]))                                 - charindex(')', reverse(t.[column])) - 1))          else null     end as result from    dbo.[table] as t 	0.00756804633620834
17060171	16795	display a table side-by-side dependent on a column	select  tr.*, tp.* from table_data tr      left outer join table_data tp      on (               tp.voucherno# = tr.voucherno#          and  tp.vouchertype = 'cp'         ) where        tr.vouchertype = 'cr' ; 	0.000349597881263344
17065098	39258	pivot over a range in sql server	select subject,   sum(case when marks > 10 and marks <= 40 then 1 else 0 end) range10_40,   sum(case when marks > 40 and marks <= 60 then 1 else 0 end) range40_60 from yt group by subject; 	0.193502631517564
17068559	5104	get total from a month and limit results mysql	select youtuber, sum(views) as viewtotal from <table> where month(date) = 5 group by youtuber order by viewtotal limit 0,10 	0
17071885	8060	count field, joins, multiple selects	select estimates.id, estimates.estimate_number,  estimates.description, estimates.meeting_date, estimates.job_date, estimates.status, estimates.price, count(estimate_versions.estimate_id) from (estimates) left outer join estimate_versions estimate_versions on estimates.id = estimate_versions.estimate_id left outer join customers customers on estimates.customer_id = customers.id where customers.key = 'jsb4nd90bn' group by estimates.id, estimates.estimate_number,  estimates.description, estimates.meeting_date, estimates.job_date, estimates.status, estimates.price 	0.226620898512863
17073575	20699	query using group by in sql	select author_id,        cnt from (    select author_id,            count(*) cnt,           rank() over (order by count(*) desc) as rnk    from posted_reviews_tab    group by author_id ) t where rnk = 1; 	0.678361730468379
17075208	12093	how to get all username status in a vb.net application	select distinct db_name(dbid),loginame, dbid  from sys.sysprocesses where [dbid] not in(0,1,4)  	0.00465871612975514
17080364	38774	incorrectly pivoting table after joining?	select   group_concat(if(meta_summary = 'content', content, null)) as content,    group_concat(if(meta_summary = 'supplemental', content, null)) as supplemental,   group_concat(if(meta_summary = 'heading', content, null)) as heading,   cms_pages.meta_filename as filename from cms_pages inner join cms_collection on   cms_collection.collection_id like concat(cms_pages.page_id, '/heading%')   or cms_collection.collection_id like concat(cms_pages.page_id, '/content%')   or cms_collection.collection_id like concat(cms_pages.page_id, '/supplemental%') inner join   cms_content on cms_collection.collection_id = cms_content.collection_id where   site_id = 53 group by   cms_pages.page_id 	0.121414497100948
17080741	36869	can we get sum of several columns in a mysql table	select a+b+c+d from ... where ... 	0.000194953390525779
17088773	34206	sql sumarize first x rows	select name,         points,        100 + sum(points * 10) over (partition by name order by some_timestamp_column) as budget from the_table order by some_timestamp_column 	0.0005993012314736
17092345	18475	calculating the percentage difference in values between two columns in sql returning 0	select station, "q4 2012", "q1 2013", "q/q",        ((cast("q/q" as float)/"q4 2012") * 100.00) as "q%" from "station figures"; 	0
17105323	35443	like '%%' have more then result	select number  from mytable  where desc like '%name%'  or desc like '%fly%' 	0.11758199429722
17106854	1854	how to efficiently retrieve data in one to many relationships	select first_table.id, case when exists (select * from second_table where first_table.id = second_table.id) then 1 else 0 end from first_table 	0.000182099759408531
17108503	11363	sqlite select query multiple where clause values	select id, . from additionalchunks where id in (? ? ? ? ? .) 	0.430172828832363
17120214	34976	php - mysql: fetch item from three tables and order by timestamp	select timestamp, postid, sourceid, fee, pay, company, elig, howto,         null as skill, null as title, null as funct, null as location, null as exper,         null as company, null as title, null as sector, null as quali, null as state from   table1 union all select timestamp, postid, sourceid, null as fee, null as pay, null as company, null as elig, null as howto,         skill, title, funct,  location, exper,         null as company, null as title, null as sector, null as quali, null as state from   table2 union all select timestamp, postid, sourceid, null as fee, null as pay, null as company, null as elig, null as howto,         null as skill, null as title, null as funct, null as location, null as exper,         company, title, sector, quali, state from   table3 order by timestamp; 	0
17124134	32915	mysql query to get count of only new users each day	select first_call_date, count(caller_id) as caller_count from (     select caller_id, date(min(call_date)) as first_call_date     from call_history      group by caller_id ) as ch group by first_call_date 	0
17156166	4224	how would the database look like?	select nama_guru, nip, nama_pelajaran, nama_kelas from tbl_jadwal j     , setup_kelas k     , setup_pelajaran p     , data_guru g where j.id_kelas=k.id_kelas  and j.id_pelajaran=p.id_pelajaran  and j.id_guru=g.id_guru  order by j.id_jadwal asc 	0.656153294345284
17162628	26844	get datetime field in specific format	select (convert(varchar(30),it.enddate,101) +' ' +         convert(varchar(30),it.enddate,8)) as end 	0.000530242983671679
17167125	27140	how to get common ids in each group from a group by sql clause?	select customer_id from usage_analysis  where usage_direction_type_id = 1 and       date_id >= 20130608 and date_id <= 20130612 group by customer_id having count(distinct date_id) = 5 	0
17167925	30491	joining two query results on the basis of one column	select     v_resident_fname as name,     sum(case i_communication_log when 1 then 1 else 0 end) as critical_notes,     sum(case i_communication_log when 0 then 1 else 0 end) as routine_notes from z_notes where dt_note_created >1332792382 and dt_note_created <1332892382 group by v_resident_fname 	0
17169613	7881	how to add values after get them	select sum(today tearning) from `sql` where username =$username date= now(); 	0.000129056214896986
17175768	3916	select rows for each 2 distinct columns in a table in sql server	select    page,   sum(name1) name1,   sum(name2) name2,   sum(name3) name3 from (select id, page, views, sitename  from table1) p  pivot (   sum(views)   for sitename in (name1, name2, name3)   ) as pvt group by    page 	0
17177032	13503	accessing parts of sub-queries to build html in a php server	select distinct propertyid, streetaddress, city, activeposting from residence.property inner join contact on residence.contact.contactid = residence.property.contactid where residence.contact.contactemailaddress1 ='$contactemailaddress1' 	0.146389864753347
17183244	37131	sql query to selecting first 3 rows as according to set and remaning should select normaly	select sn,status from mytable order by status desc,sn 	7.4983563378714e-05
17194091	3736	find the highest number in a column	select max(questionnaireid) as maxid from `questionnairequestions` 	0
17195928	13946	access sql - given two dates, return the dates of the previous period	select dateadd("m",datediff("m",enddate,startdate)-1,startdate) as startdateprevious ,dateadd("m",datediff("m",enddate,startdate)-1,enddate) as enddateprevious from querydates; 	0
17210097	10754	selecting a substring if it's not an integer	select substring(postcode,1,1) as one, if(substring(postcode,2,1) regexp '^-?[0-9]+$', null, substring(postcode,2,1)) as two  from postcodes 	0.0228157291972558
17211125	5205	separate a string based on a second table	select number,         coalesce(prefix, 'unrecognized') as prefix,         substr(number, length(prefix)+1) as localpart,        coalesce(name, 'unknown') as region from phone left join prefix on substr(number, 1, length(prefix)) = prefix 	0
17212888	28213	where not exists x amount of times	select *    from timescheduletable   where exists ( select employeeid                    from appointmenttable                  where employeeid= @pemployeeid                     and ...                  group by employeeid                 having count(*) <= 3 ) 	0.00148415032909276
17218753	3490	how to run mysql sub queries to count the records.	select a.id, count(distinct b.id) total_groupb, count(distinct c.id) total_groupc from groupa a  left join groupb b on a.id=b.groupa_id  left join groupc c on b.id=c.groupb_id  group by a.id 	0.0336927881913216
17226556	37405	transform a table in sql	select city, sum(fromcity) as fromcity, sum(tocity) as tocity, sum(via) as via from ((select fromcity as city, 1 as fromcity, 0 as tocity, 0 a via        from t       ) union all       (select tocity, 0, 1, 0        from t       ) union all       (select via, 0, 0, 1        from t       )      ) t group by city 	0.0941477445235763
17229011	32907	how to get count of matching strings in a large table	select replace(name, ' (duplicate)', ''), count(*) from mytable group by 1 	0.000100644246385928
17229584	17422	merge three mysql entries to one entry	select a,group_concat(b) b, group_concat(c) c from table  group by a; 	0
17229664	28664	query data from two tables	select name, your, fields  from user_details left join user_timer on user_details.id = user_timer.user_id where checkin_date between '$startdate' and '$enddate' 	0.00275877194774418
17274881	31675	how to receive two values from a subquery sqlite	select p.id, p.first_name, p.last_name, p2.id as pet_id, p2.name as pet_name from person as p inner join person_pet as pp on pp.person_id = p.id inner join pet as p2 on p2.id = pp.pet_id where  p2.purchased_on > '2004/01/01 0:0:0 am' 	0.00173907253975942
17280816	35460	sql: creating a new table with query results	select a.[cusip number],        ... into newtable from  dbo.mbs032013 a ... 	0.224338891587334
17286893	29099	php / mysql -> best way to make a indexed/categorized list	select group_concat(name) as names, category from table_name group by category 	0.129342099583626
17294131	2734	display only the last 300 mysql results with a php pagination system	select * from (select * from $tablename where type='6' and country_code='gb' order by auto_incerment_id desc limit 300) as a order by auto_incerment_id asc limit $start, $limit 	0.000177563906035443
17299107	16295	take the max value of a column in a sql table	select distinct s.prodotto, d.codprod, max(d.idprod) from d_prod d, app_sales s where d.codprod = s.prodotto group by s.prodotto, d.codprod 	0
17321056	31930	mysql - two dependent weighted averages in a single query	select sum(hours_transit * load_transit) / sum(hours_transit),        sum(hours_standby * load_standby) / sum(hours_standby),        (sum(hours_transit * load_transit + hours_standby * load_standby)) / sum(hours_transit + hours_standby) from table1 	0.00327415593810211
17322686	30292	django: integrityerror: duplicate key value violates unique constraint	select  n.nspname as schema_name,         co.conrelid::regclass as table_name,         co.conname as constraint_name,         pg_catalog.pg_get_constraintdef(co.oid, true) as constraing_def from pg_constraint co inner join pg_catalog.pg_class cl on cl.oid = co.conrelid left join pg_catalog.pg_namespace n on n.oid = cl.relnamespace where co.conname = 'pegasus_config_scanner_id_name_key' and co.contype = 'u' 	0.000640560726459171
17326459	9209	fastest way to access a row in sqlite using a row number	select * from test order by daterecorded desc limit 200 offset 600 	0.000872044625056823
17329617	2179	multiple rows in aggregate function	select      e.[eid], e.[cn], e.[an], m.[milestone], e.[status], max(m.[id]) as milestone_id, (         select max([due date]) from [pilot milestone] as m2 where m2.[id]=max(m.[id]) and m2.[eid]=m.[eid]         ) as due_date from      [pilot milestone] as m     inner join [pp engagements] as e on e.[eid]=m.[eid] group by e.[eid], e.[cn], e.[an], m.[milestone], e.[status] 	0.356640229983175
17334308	9203	retrieving and count no. of rows in birthdate to age with multiple where clause in a single query?	select age_range, count(*) from (     select case         when yearsold between 0 and 5 then '0-5'         when yearsold between 6 and 10 then '6-10'         when yearsold between 11 and 15 then '11-15'         when yearsold between 16 and 20 then '16-20'         when yearsold between 21 and 30 then '21-30'         when yearsold between 31 and 40 then '31-40'         when yearsold > 40 then '40+'         end as 'age_range'         from (             select year(curdate())-year(date(birthdate)) 'yearsold'              from mytable         ) b ) a group by age_range 	8.58650168261166e-05
17337309	25437	show text instead of id of foreign key in gridview	select a.id, customer, contactperson, model, serialno, status, b.type, value, invoiceno      from backbillcustomer a inner join foregnkeytablename b  on a.type=b.id and status = 'open' 	0
17345504	349	position value of each field in query	select *, row_number() over (partition by parent order by name) as position from (     select i.id, l.lev1 as name, null as parent     from idtable i       join leveltable l on i.name = l.lev1      union     select i.id, l.lev2 as name, (select j.id from idtable j where j.name = l.lev1)     from idtable i       join leveltable l on i.name = l.lev2      union     select i.id, l.lev3 as name, (select j.id from idtable j where j.name = l.lev2)     from idtable i       join leveltable l on i.name = l.lev3 ) as q 	0
17345880	39887	how to trim everything after certain character in sql	select replace(left(email, charindex('@',email)-1),'_',' ') from [dsr].[dbo].[rca_dashboard] 	0.00662979844157645
17352323	28359	parse xml using t-sql and xquery - searching for specific values	select    @xml.value('(/properties/property[name = "dismiss_setting"]/value/text())[1]', 'nvarchar(100)') as dismiss_setting,   @xml.value('(/properties/property[name = "show_setting"]/value/text())[1]', 'nvarchar(100)') as show_setting,   @xml.value('(/properties/property[name = "default_setting"]/value/text())[1]', 'nvarchar(100)') as default_setting 	0.0845015336753151
17361081	24748	how to get the latest records of the multiple values of same column in postgresql?	select *  from dns_lookup_table lut  where not exists (    select *    from dns_lookup_table nx    where nx.url = lut.url      and nx.update_time > lut.update_time    ); 	0
17362506	1912	sql query to find train between stations	select    train from    dbo.traintime where    code in ('abc', 'xyz') group by    train having    count(distinct code) = 2 ; 	0.0558094840300061
17368363	22576	sql server 2005 query between two tables	select p.*, rm.regionid, rm.clientnum from provider p inner join rp on p.id = rp.provider inner join rm on rm.regionid = rp.regionid 	0.0785262793621548
17377406	32220	what is the sql query to select the id's of same name?	select group_concat(sample.id) as ids, sample.name from sample group by name; 	0.000214650126887805
17378273	40195	error when trying to update a row with a random value	select id,floor(abs(checksum(newid())) / 2147483647.0 * 3 + 1) as rn into #tmp from name update name set surname=data  from #tmp join sampledata sd on sd.rownumber=#tmp.rn where #tmp.id=name.id select * from name 	0.0585080547080061
17390871	27514	mysql : select count group by day with custom starting and ending hours for a day	select   month(l.join_date - interval 14 hour) mois,   day(l.join_date - interval 14 hour) jour,   count(distinct l.customer) nbj,   str_to_date(l.join_date - interval 14 hour,'%y-%m-%d') ordre from log_waitingtime l group by   month(l.join_date - interval 14 hour),   day(l.join_date - interval 14 hour) order by   ordre asc 	0
17397062	23075	sybase ase data grouping	select t1.* from table1 t1 where t1.lastmodificationdate  = (select max(t2.lastmodificationdate)                                   from table1 t2                                   where t2.effectivedate = t1.effectivedate                                   and t2.id = t1.id) 	0.10588891979416
17403794	31339	sql if exists or where exists?	select a.item, a.cnumber, a.location, a.date from yptimport a where not exists (select * from ypimport b  where a.cnumber = b.cnumber and a.location = b.location and a.date= b.date) 	0.751467641149062
17407091	39485	calculate the similarity(through a formula) between two records with a sql query	select id,        ((case when min(firstname) = max(firstname) then 1.0 else 0 end) +         (case when min(lastname) = max(lastname) then 1.0 else 0 end) +         (case when min(dob) = max(dob) then 1.0 else 0 end) +         (case when min(parentlastname) = max(parentlastname) then 1.0 else 0 end)        ) / 4.0 as similarity from t group by id; 	0.000570761774500383
17408062	11164	mysql query building - referral count (same row join?)	select referredby, count(*) from thistable      group by referredby order by cnt desc; 	0.0657577748197377
17410135	22059	how do you write a microsoft access query that outputs the frequency of elements in a field as a percentage?	select lettervalue, cdbl(100.0*count(*)/tot.tot)&'%' as qty from sampletable st,      (select count(*) as tot       from sampletable st      ) tot group by lettervalue; 	0.000797532685151422
17411987	2736	adding columns you created in mysql?	select username, @n := @n + 1 ranking, `1st places`, `2nd places`, `3rd places`, `top5`, `top3, `1st places` + `2nd places` + `3rd places` as `total finishes` from ( select username, sum(case when rating = 1 then 1 else 0 end) `1st places`, sum(case when rating = 2 then 1 else 0 end) `2nd places`, sum(case when rating = 3 then 1 else 0 end) `3rd places`, sum(case when rating < 6 then 5 else 0 end) `top5`, sum(case when rating < 4 then 5 else 0 end) `top3` from table1 group by username order by `1st places` desc ) q, (select @n := 0) n 	0.0366962084607725
17424177	32603	how to find rows that has values that exists with criteria 'a' in a table but does not exist with criteria 'b'?	select no from   ( select no, max(field1) as maxfield1     from tablex     group by no, type   ) as tmp group by no having min(maxfield1) > 0 ; 	0
17427020	15365	postgresql at least 2 sales in the same day	select id,         name,        lastname,        seller,        date,        item from (   select id,           name,          lastname,          seller,          date,          item,          count(*) over (partition by date, seller) as cnt    from the_table ) t where cnt >= 2; 	0
17428726	7013	mysql: return a number of matches	select r.id,         r.text,         ((r.text regexp 'foo') +         (r.text regexp 'bar') +         (r.text regexp 'choo')        ) as matches  from results as r where r.text regexp 'foo|bar|choo' and r.text not regexp 'man' 	0.000845111604883701
17430139	13951	sql getting data using other table + a value	select * from following f inner join users u on f.user_id = u.user_id where u.user_id = x and u.fullname like '%a%' 	0.000525524110761889
17436962	37753	how do i see which columns throughout my database reference one particular column as a foreign key? like a "reverse" foreign key?	select table_schema, table_name, column_name from information_schema.key_column_usage where (referenced_table_schema, referenced_table_name) = ('mydatabase', 'products') 	0
17461086	3565	how to get accumulated data using sum, group by function	select datename(month , day) , sum(column1) , sum(column2) .. from (yourquery) as a group by datename(month , day) 	0.142491917811517
17464680	5855	mssql totals per day for a month	select date,   sum(case when [program label] = 'salary day' then count else 0 end) [salary day],   sum(case when [program label] = 'monthly' then count else 0 end) [monthly],   sum(case when [program label] = 'policy' then  count else 0 end) [policy],   sum(case when [program label] = 'worst record' then count else 0 end) [worst record] from totals group by [date]; 	0
17464831	32628	php code to extract data month wise	select     name,      email,     phone,     dob,     bank_account_no from     user where     date_format(application_date, '%y-%m') = date_format(now(), '%y-%m') 	0.000788269000092684
17465568	38445	sql checking substring in a string	select * from table where     mapping like '%,iv=>0j,%'     or mapping like '%,iv=>0j'     or mapping like 'iv=>0j,%'     or mapping = 'iv=>0j' 	0.238208681880699
17465879	25389	get id where group by partnerid, max(changedate) - fast	select id ,  partnerid ,  changedate  from  ( select  row_number() over (partition by partnerid  order by changedate  desc) as row, id   partnerid ,    changedate    from sampletable ) t where row=1 	0.0131583025820361
17466751	27699	count of number of records in each time interval with mysql	select     count(date_action) as count,     case          when minute(date_action) between 0 and 14 then '00'         when minute(date_action) between 15 and 29 then '15'         when minute(date_action) between 30 and 44 then '30'         when minute(date_action) between 45 and 59 then '45'     end as intervals from     clients where     hour(date_action) = 09     and day(date_action) = 15     and month(date_action) = 07     and year(date_action) = 2013     and rep_id = 28 group by intervals 	0
17509177	37520	mysql sum up rows and columns	select        id,        sum(item_1+item_2+item_3) as item_sum   from yourtable   group by id   order by item_sum desc; 	0.00298896672778807
17521648	16187	compare sum of value with other value of same id in difference table	select *  from (select invoice.invoiceid,               invoice.invoiceamount,               pays.invoiceid,               pays.paymentamount as pays,               invoice.invoicedate ,              (select sum(a.paymentamount)                  from `payment from customer` a                 where a.invoiceid = invoice.invoiceid) totalpays         from `payment from customer` as pays join invoice            on (pays.invoiceid=invoice.invoiceid) ) temp where invoicedate > totalpays 	0
17524991	25436	myqls group by or order by	select c1, max(c2) as maxc2 from mytable where date='$sl_date' group by c1 order by maxc2 desc 	0.548177994131571
17545413	2171	concatenate a pivot table output	select * from     (        select c.registration as ''reg.'', p.name,          cast(sum(j.estimatedtime) as varchar(max)) + '/' +         cast(sum(j.actualtime) as varchar(max)) as [x]     from    jobdetails  as j     inner join jobphases p on p.id = j.phaseid     inner join jobs job on job.id = j.jobid     inner join cars c on job.carid = c.id     where job.status = 1 or job.status = 0     group by c.registration, p.name ) jobdetails pivot (   max(x)     for name in (' + @cols + ') ) pvt 	0.0280876253721241
17545490	33907	what while populating list we find a column null	select * from fruits where fruita is not null; 	0.0379521238426767
17545859	28296	sql server: fill null fields from not null column for multiple rows having same id	select t1.orderid, t1.productcode, max(isnull(t2.coupon,'')) as couponcode, t1.customername from (     select  o.orderid,od.productcode,od.couponcode as coupon,c.customername     from orders o     inner join orderdetails od on o.orderid=od.orderid     inner join customers c on o.customerid=c.customerid )t1 inner join (                 select  o.orderid                 from orders o                 inner join orderdetails od on o.orderid=od.orderid                 inner join customers c on o.customerid=c.customerid             )t2 on             cast(t1.orderid as varchar)=             cast(t2.orderid as varchar) group by t1.orderid, t1.productcode, t1.customername order by t1.orderid 	0
17548681	9780	avoiding a nested subquery for the single table	select sales_id, max(revision) from sales group by sales_id having max(revision) = 0; select sales_id, max(revision) from sales group by sales_id having max(revision) = 1; 	0.378208386464375
17551385	15682	postgresql aggregate of aggregate (sum of sum)	select d.name, sum(s.amount) from sales s join department_employees de on de.worker_id = s.worker_id join departments d on d.id = de.department_id group by d.name 	0.16728526496847
17555038	25461	finding duplicate values in different columns on the same row	select * from t where exists       (select 1        from (values                     (preparedby)                   ,(prelimapprovalby)                   ,(approval1signer)                   ,(approval2signer)) as x (n)       where nullif(n, '') is not null       group by n       having count(*)>1      ) 	0
17565376	37631	mysql query - join different tables based on a precondition (value retrieved from a different table)	select         c.type as type,        coalesce(m.name, f.name, s.name) as membername,         coalesce(m.age, f.age, s.age) as memberage,         coalesce(m.location, f.location, s.location) as location from club_members c left join male_members m on c.name=m.name and c.type='male' left join female_members f on c.name=f.name and c.type='female' left join senior_members s on c.name=s.name and c.type='senior' where c.id='your value' 	0
17570676	14849	mysql select group by count(*) union into delimited string?	select group_concat(concat_ws(',', playerid, r1, r2) separator ';') from (   select   playerid, sum(rank=1) r1, sum(rank<5) r2   from     result   group by playerid ) t 	0.0226988318649734
17573863	13971	copy data from odbc connection to local database	select a.firstname, a.lastname, b.city, b.state, b.zip into _temp_report from customers a join addresses b on a.customer_id = b.customer_id 	0.0406828547935987
17577072	38403	two results in a single query	select (select name from names where id = 2) as name1, (select name from names where id = 3) as name2 	0.0164311988006832
17577152	34257	mysql getting a record closest to one year old	select abs((curdate() - interval 1 year) - date_column) as diff  from table  order by diff  limit 1 	0
17579414	3495	derive grouped meaning from multiple rows	select      t.batchid,      case          when exists(select 1 from #t where taskstatus in (2,3) and batchid = t.batchid) then 1          when exists(select 1 from #t where taskstatus=1 and batchid = t.batchid) and exists(select 1 from #t where taskstatus=4 and batchid = t.batchid) then 1         else 0      end processing   from #t t group by batchid 	0.000701800828799904
17582050	818	how can i select rows from a table when i max(cola) and group by colb	select x.*       , (scorea+scoreb)/2 avg_score     from scores x     join       ( select player, max((scorea+scoreb)/2) max_avg_score from scores group by player) y       on y.player = x.player      and y.max_avg_score = (scorea+x.scoreb)/2; 	0.00133540722071522
17582139	15734	how to do mysql search which excludes duplicate records	select id, mls_id, address, agent_id from mytable t1 where t1.agent_id=1 and t1.id =      (select min(t2.id)       from mytable t2       where agent_id=1 and t2.mls_id=t1.mls_id       group by t2.mls_id) 	0.00204105220016341
17583555	29135	select with subquery avoid running more than once?	select       col_a     ,col_b     ,col_c     ,case          when t.whatevercol is not null then 1         else 0      end case as col_d,     t.whatevercol from     mytable, (select ...{a very complicated query}...) t 	0.469253504041411
17583681	4415	how to order articles by both quality score and publish date?	select *, (score/power(((now()-published)/60)/60,1.8)) as rank from posts order by rank desc; 	0.00725036568654824
17615598	7664	get specific period of each year in mdx query	select {[measures].[employee recordable case rate]} on columns,  {[dim time].[year - quarter - month].[quarter].members } on 1 from [model]  where ({ [dim time].[year].[2006]:[dim time].[year].[2012]}, [dim time].[quarter].[q1]) 	0
17617848	20095	temporarily replacing values in sql or subbing in values via sql	select  x.date,  sum(x.hyp_mv* x.retmtd)/sum(x.hyp_mv) as weightedreturns from     (     select      date,     asset,     retmtd,     (case asset      when 'sp500' then 200000      when 'ust2' then 200000      when 'ftse' then 600000      end) as hyp_mv     from [dbo].[assetret]     where     asset in ('sp500','ust2','ftse')     and     date >=  '12/31/2000'      )x group by x.date order by x.date 	0.0652654773537804
17619363	38639	query explode multiple values in one column	select cc.company_name,group_concat(c.name) from company_classifications cc  inner join classifications c  on c.id = find_in_set(c.id,cc.classifications) group by cc.company_name; 	0.00684531335820294
17681904	25735	sql sum(count) of specific columns and group sum by month	select year_, month_, sum(counts) from (         select year(dateadd(mm,datediff(mm,0,starttime),0))'year_'               ,datename(month,dateadd(mm,datediff(mm,0,starttime),0))'month_'               ,testname               ,case when testname = 'poe business rules' then (count(testname)*36)                      when testname = 'submit' then (count(testname)*6)                      else 0                 end 'counts'         from vexecutionglobalhistory         group by year(dateadd(mm,datediff(mm,0,starttime),0))                 ,datename(month,dateadd(mm,datediff(mm,0,starttime),0))                 ,testname         )sub group by year_, month_ order by cast(cast(year_ as char(4)) + month_ + '01' as datetime) 	0
17721985	26912	order by with distinct name	select distinct pageorderid,pagename from screenmaster order by pageorderid 	0.104348612745626
17727361	12645	can i create a view that will query a table from another sql server on another server but same domain	select * from "linkedserver".dbo.atable 	0
17734739	25384	mysql query to get age from date of birth	select id, pseudo, nom, prenom, sexe, ville,     floor(datediff (now(), date_naissance)/365) as mage  from user  where sexe = 'homme' and  floor(datediff (now(), date_naissance)/365) between 18 and 25  or ville = 'bordeaux' 	0
17745713	3672	sql statement to retrieve the last entry value from database	select top 1 invoiceno  from buyinvoice order by right(invoiceno,4) desc,   right(invoiceno, 6) desc,    invoiceno desc 	0
17752123	21638	how to sum fields in two table and group by date	select l.date_created as c_date_created, sum(l.shell) as c_shell, sum(lp.c_harga) as c_harga, l.* from laporan l left join (select laporan_id,                   sum(harga) as c_harga            from laporan_pengeluaran            group by laporan_id) as lp on l.id = lp.laporan_id where l.date_created between '2013-07-01' and '2013-07-05' group by l.date_created order by l.date_created asc 	0.000336389571174776
17774736	3546	count strings in database table	select count(*) from yourtable where yourcolumn = 'wrong'; 	0.0257267771018999
17786296	21838	ms access - link to query in another access database	select [remotequeryname].* from [remotequeryname] in 'c:\remotedatabase.mdb' 	0.281566166282936
17787209	34476	how to make a mysql query to include rows once of a column based on another?	select r.*       from (select b.*               from banner b             where b.comune_number = 9 union all            select b2.*              from banner b2             where b2.comune_number = 0          group by b2.image) r  group by r.image; 	0
17796503	31420	sql query select all rows except one	select * from `jogos` where intcategoria <> 11 order by rand() 	0.000531633468310036
17798712	39701	mysql query data based on time	select c.name, invoice_number,         (select rate           from company_rate           where company_id = i.company_id            and effective_date <= i.paid_date          order by effective_date desc          limit 1) rate,        paid_amount,        paid_date   from invoice i join company c     on i.company_id = c.id 	0.00269687126996398
17809868	33436	counting lines in a list	select count(color) as cnt, color from yourtable group by color 	0.00269136817440357
17818703	20102	sql query one to many relationship join without duplicates	select columnlist,  rn = row_number() over (partition by sales.salesid order by payment.paymentid) from sales join payments on sales.salesid=payments.salesid 	0.0727331437861541
17819259	6060	group mysql count values in comma separated field	select count(*) from users a  inner join mechanics b  on (find_in_set(b.id, a.mechanic_id) > 0) where b.id = '{$id}'  group by b.id 	0.00012180119576912
17829089	24332	mysql. deduct sum(d.amount) from sum(c.amount) and group by (depending on) values in other column	select transactionpartnername, sum(if(cast(debitaccount as unsigned) in (?), -amount, amount))  from 2_1_journal data  where (cast(debitaccount as unsigned) in (?) or cast(creditaccount as unsigned) in (?))  group by transactionpartnername 	0
17829643	7948	determine entrys with "missing" subsequent entry in sql	select * from  table as t1 left outer join table as t2 on(t1.name=t2.name and t2.event='sign out') where t1.event='sign up' and t2.name is null 	0.0552752832498497
17841209	7219	sql query: comparing two dates in returned record	select  tblone.serviceid, tbltwo.accountnbr,     tbltwo.acctname, tblfour.servicename, tblone.status,     tblthree.begindate, tblthree.enddate,     tblone.serviceyear, tblfive.servicebegin,     tblfive.serviceend from  ((tbltwo inner join tblfour    on  tbltwo.accountnbr=tblfour.accountnbr) inner join (tblthree inner join tblone    on  tblthree.serviceid=tblone.serviceid)    on  tblfour.clientid=tblone.clientid) inner join tblfive    on  tblone.contractid=tblfive.contractid where tblthree.enddate > tblfive.serviceend; 	0.000481475250454181
17841677	11558	left join on foreign keys	select a.id      , a.name      , c.veg_type   from a a   left   join b b     on b.object_id = a.id   left   join c c     on c.veg_id = b.veg_type_ref 	0.0665769450974424
17842926	3323	mysql counts based on timestamps?	select count(q.id) from `profile_questions` q  left join profile_answers a on q.id = a.question_id                              and q.user_id = a.answered_by where q.user_id = 5 and a.answered_by is null 	0.00035589494903875
17868245	40313	how to convert a mysql datetime column to just date?	select * from alerts_to_send    where  date_format(date_to_send,'%m-%d-%y') = date_format(now(),'%m-%d-%y') 	0.00143675318396732
17899066	10342	get rank within table for any number	select count(*)+1 rank from bids where bid_amount > 15 	0.000792223113860728
17911334	37901	return specific text from mysql using locate and substring	select        substring_index(         left(description,            greatest(locate(' yards (', description),                    locate(' yard (',  description))-1), ' ', -1) from nflpxp 	0.0379242168414894
17917404	9880	calculate summation of all columns	select sum(column) as column, sum(column2) as column2, sum(column3) as column3 from result where username = '$table' 	0.00028556697142644
17922494	4068	multiple select statements in one, creating new columns	select      (select pos.pdposition       from positiondata pos       where pos.positionid = 1765) as [region 1]    ,(select pos.pdposition       from positiondata pos       where pos.positionid = 1767) as [region 2] 	0.00564074761478449
17922779	29943	get the time from the last post in seconds	select unix_timestamp() - unix_timestamp(mydatetime) from ... 	0
17923407	21249	first and last record for a user in a given time period in one query	select t.id, t.user_id, t.date, t.other_columns from table t where user_id = 1     and date = (         select min(date)         from table         where user_id = t.user_id             and date > date_sub(curdate(), interval 24 hour)) union all select id, user_id, date, other_columns from table where user_id = 1     and date = (         select max(date)         from table         where user_id = t.user_id             and date > date_sub(curdate(), interval 24 hour)) 	0
17926520	38334	find a field that contains text but give preference to matches at the start of the field	select *, locate('term', field) as rev_score from table where field like "%term%" order by rev_score desc limit 20; 	0
17927296	27431	sql multiple tables with	select distinct clientid,                  clientname,                  telephone  from   (select t1.clientid,                 t1.clientname,                 t2.telephone1 as telephone          from   client t1                 inner join (select clientid,                                    telephone1                             from   address                             where  telephone1 is not null)t2                         on t1.clientid = t2.clientid          union          select t1.clientid,                 t1.clientname,                 t2.telephone2 as telephone          from   client t1                 inner join (select clientid,                                    telephone2                             from   address                             where  telephone2 is not null)t2                         on t1.clientid = t2.clientid)t 	0.175778296350628
17928458	5324	sql: finding db entry that ends a given string	select * from table_name where :userparam like concat('%', domain) 	7.12001838663073e-05
17928854	32081	error: order by items must appear in the select list if select distinct is specified	select      [theme].[name], [themetype].[type]  from      [theme]  left outer join      [themetype] on [theme].[themetypeid] = [themetype].[pk_themetype] join      [producttheme] on [producttheme].[themeid]=[theme].[pk_theme] where      producttheme.productid like '%'      and producttheme.themeid = theme.pk_theme      and coalesce([theme].[themetypeid], 'null') like '%[0-9]%'  group by     [theme].[name], [themetype].[type]  order by      case when [themetype].[type] is null             then 0             else 1      end, [theme].[name] 	0.0090162570316434
17931256	41094	mysql select distinct values from two table that have a common key	select distinct quotes.quote_id, quote_name, item_name from quotes, quote_items  where quotes.quote_id = quote_items.quote_id group by (quote_id ); 	0
17933397	35352	selecting data from two mysql tables at once in php	select country, sum(totalclicks) as totalclicks from  ( select count(id) as totalclicks, country from adverts_analytics_user_clicks where advertid =:advertid group by country union all select count(id) as totalclicks, country from table 2 where advertid =:advertid group by country ) group by country 	0
17934887	29554	formatting decimal with sql	select proc_p,right('000'+cast(cast((cast(proc_p as decimal(4,0))/100) as decimal(4,2)) as varchar(5)),5) from test 	0.767253309597963
17952878	10546	sql query union	select a.refnumber,        c.firstname,        c.lastname,        c.company,        a.registrationtype,        b.yesnoentry from reg a, reg b, regperson c   where a.refnumber=b.refnumber   and a.regpersonid=c.regpersonid   and a.registrationtype !=''   and b.yesnotoggle=1   and b.yesnoentry=1; 	0.697361477975413
17958247	22082	only filter out what some parameters have in comon with sql	select   items.itemid, group_concat(itemrelation.itemrelto) as itemrelto, items.catid, items.title, items.image, items.desc, items.timestamp from items inner join itemrelation  on items.itemid = itemrelation.item where itemrelto in (30,31) group by itemid having count(items.itemid) > 1 	0.145162427130473
17961052	22693	query to complete empty spaces on table in postgres	select date_format(a.date,'%m/%d/%y') as date, b.value as value  from table_a as a join      (select b1.date as start, ifnull(min(b2.date),'9999-12-31') as end, b1.value as value             from table_b as b1 left outer join table_b as b2             on b1.date < b2.date             group by b1.date) as b on a.date >= b.start and a.date < b.end 	0.182764558784593
18000733	23002	joining two tables through a join in an already existing mysql query	select `i_resident_id` as id, resident_fname as firstname, `resident_lname` as lastname,                          sum(case i_communication_log when 1 then 1 else 0 end ) as critical_notes,                          sum(case i_communication_log when 0 then 1 else 0 end ) as routine_notes,                         sum(1) as total_notes                         from z_notes                         left join user_roles on z_notes.i_resident_id = user_roles.fk_user_id                         where dt_note_created > '$from'                         and dt_note_created < '$to'                         and facility_id = '$facility_id'                         and user_roles.fk_role_id != 4                         group by v_resident_fname                          order by total_notes $asc_des"; 	0.00742763915971112
18017020	27990	mysql/php/smarty - how can i retrieve 2 diffirent sets of rows in one row?	select c.*,    group_concat(g.imglink) as links,   group_concat(g.imgthumb) as thumbs from mycars c  left outer join mycars_gallery g  on c.car_id = g.car_id  left outer join mycars_details d  on c.car_id = d.car_id  where c.status = 1 and c.car_id = 27 group by c.car_id; 	0
18041435	23213	how to order by one column and make elements with same 2nd column contino uous?	select tbl.* from     ( select max(id) as m, resolvedid from tbl group by resolvedid) as driver     join tbl      on driver.resolvedid = tbl.resolvedid      order by driver.m desc, tbl.id desc, driver.resolvedid; 	0
18050272	13720	mysql joining tables where clause	select member.*,c.* from member inner join ( select distinct member.id as  mid from member  inner join member_card      on member_card.member = member.id  and ( member.lastmodifieddate >= sincedate       or member_card.lastmodifieddate >= sincedate ) ) a on a.mid=member.id inner join member_card c on c.member=a.mid 	0.50162690164258
18057617	20467	get mysql sum after mathematical operation	select sum(val) from (   select (sum(dr.drv)/100)*     (st.suppliers1_value+st.suppliers2_value+st.suppliers3_value+st.suppliers4_value)     as val ) as a 	0.139897964056705
18069540	16091	multiple field entries, best approach	select * from   users2events where   id_user=(select id from users where name='bill') and place=1; 	0.00151525334800817
18072405	19453	where do i find the database's own current timezone in mysql?	select variable_value from information_schema.global_variables where variable_name='time_zone' 	0.000640683860738421
18072501	19029	statement to count(*) related rows on other table	select d.name,           (select count(1) from patient_list p where p.dentist_id = d.dentist_id)      from dentist_list d order by 2 asc  	0.00017315063578188
18119017	15607	identifying tables from a given database	select  table_name  from information_schema.columns  where column_name = 'columnname' 	0.000421751461725683
18121940	6433	postgres: getting the highest matching log associated with a record?	select m.name,l.event from log l inner join model m on l.modelid = m.id  where l.id in  (   select max(id) from log group by modelid ) 	0
18126593	13779	sum over multiple rows, return top 10 (best seller) ids from my database	select id,sum(quantitie) as quan from produitgroup by id order by quan desc limit 10 	0
18128895	28026	replace spaces, tabs and carriage returns	select ... replace(rs.notes,chr(10)) ... 	0.720989606538627
18134788	7971	how to join two tables using mysql	select *      from orders      inner join members         on orders.coordinatelist_id = members.members_member 	0.0549069690393132
18150249	14297	select a value given multiple rows	select distinct `a` from `t` as `t1`     where not exists (         select 1 from `t`              where `t`.`a` = `t1`.`a`              and `b` in (2,3)     ); 	0.00012924311347216
18157930	12057	count of different values in mysql table not adding correctly	select count(distinct country) from tpf_parks 	0.0125468850312551
18160623	39835	trying to select rows from different tables	select bossid, status, couponnumber, fk_prizeid, fk_winnerid, prizename, firstname, lastname, dob , '', '' , '', '', '', '' 	0.0001573510061532
18163970	11689	return only one row of a select that would return a set of rows	select * from mytab where not is_available order by id asc limit 1 	0
18180356	34279	order by data depending on a specific value of column	select t1.* from table1 as t1     left outer join table1 as t2 on t2.id = t1.id and t2.pid = 2 order by t2.name, t1.pid 	0
18183903	300	select conditionally limited data from a single table	select  id, title, cat from    (   select  id,                     title,                     cat,                     @r:=if(@cat = cat, @r+1, 1) as rownum ,                      @cat:= cat as cat2              from    t_news,                     (select @cat:= 0) as cat,                     (select @r:= 0) as r             order by cat, id         ) t where   rownum <= 5; 	0.000271977800678456
18197605	21267	mysql time difference between rows matching criteria	select      t1.trackid,     t2.date - t1.date from     table t1     join table t2 on t2.trackid = t1.trackid and t1.action = 0 and t2.action = 3 where t1.date between '2013-08-12 00:00:00' and '2013-08-12 23:59:59' 	4.98927344086464e-05
18199117	4532	retrieve rows via join and datetime query where datetime is in past and not in future	select distinct `users`.id from `users`  left outer join `events` on events.user_id = users.id left outer join `purchases` on `purchases`.id = `events`.purchase_id where events.starts_on <= '2013-07-15' or events.starts_on >= '2013-08-12' group by `users`.id having min(starts_on) <= '2013-07-15' and max(starts_on) < '2013-08-12' limit 0, 30; 	0.000492358601675689
18202771	40400	fetch data in ms sql 2008	select  district_name,         sum(                 case                      when datediff(day,created_date, getdate()) < 10                         then 1                     else 0                 end             ) [<10 days],         sum(                 case                      when datediff(day,created_date, getdate()) >= 10 and datediff(day,created_date, getdate()) < 20                         then 1                     else 0                 end             ) [>10 and <20 days],         sum(                 case                      when datediff(day,created_date, getdate()) >= 20                         then 1                     else 0                 end             ) [>20 days] from    your_tables_here group by    district_name 	0.141937192008735
18209623	35822	intercepting select query and invoking a registered .net module	select value from dbo.clrudf('v001') 	0.411578190177345
18215680	2836	mysql: assigning column name / handle to a subquery	select be.id, be.title,         (select (count(bec.blog_entry_id))         from blog_entry_comments bec          where be.id = bec.blog_entry_id) as blog_entry_comments_total,         (select (count(bec.blog_entry_id))          from blog_entry_comments bec          where be.id = bec.blog_entry_id and bec.live = 0) as blog_entry_comments_disabled from blog_entries be; 	0.384451650308842
18217015	24154	need some help hiding duplicates from results mysql	select p.*  from posts p  left join following f      on f.user_id=1 and p.post_user_id = f.follower_id  where (post_user_id=1      or f.follower_id is not null)      and (post_data_id not in (select post_id                               from posts p                                left join following f                                    on f.user_id=1 and p.post_user_id = f.follower_id                                where (post_user_id=1                                    or f.follower_id is not null))         or post_data_id is null) order by `post_id` desc; 	0.479096645827534
18231110	14518	extracting value from subquery to main query	select  pid ,         t.j  from    d         inner join ( select f2.fid ,                             f2.j                      from   f f2 ,                             ( select    f.j                                from      f f                               group by  f.j                               having    count(*) >= 2                             ) f                      where  f.j = f2.j                    ) t on d.fid = t.fid where   r = 'something' group by pid, t.j having  count(*) >= 2 	0.013818908989805
18241294	16606	sql to return user list with the picture count from another table	select u.id_user as id, u.name, count(p.id_user_picture) as pics      from user as u      left join user_picture as p on p.id_user = u.id_user     group by u.id_user, u.name; 	0
18256453	4719	mysql if... select statement whilst retaining column headers	select 'gridimage_id','nateastings','natnorthings', 'view_direction'    union   select gridimage_geo.gridimage_id, gridimage_geo.nateastings,   gridimage_geo.natnorthings, gridimage_geo.view_direction into outfile 'geo.csv'   fields terminated by ',' optionally enclosed by '"'  from geograph_db.gridimage_geo, geograph_db.image_numbers where image_numbers.column1 = gridimage_geo.gridimage_id; 	0.106096311341781
18261565	31015	oracle sql - determine if a timestamp falls within a range, excluding date	select * from orders     where to_char(my_timestamp,'hh24:mi:ss.ff3')     between '00:00:00.000' and '01:00:00.123'; 	0
18272896	26216	combining quries on the same table in to one query	select  sum(if(`group` = 'order' and `status` = 'accept', 1,0)) as `accept`, sum(if(`group` = 'quotation' and (`status` = 'final' or `status` = 'manualprice'), 1,0)) as `price` from `status`  where `groupid` in (98779,98780)  and `group` in ('order', 'quotation')  and `status` in ('accept', 'final', 'manualprice') 	0.000357109063713568
18276140	17944	sql query gives more than one, repeated data	select bam.balanceaccount, bam.cid from customer cr  join balanceaccountmovement bam on bam.cid = cr.id      and bam.balanceaccount > 0      and date = (select top(1) date                   from balanceaccountmovement bam2                   where bam.cid = bam2.cid                  order by date desc) 	0.100518674648141
18308103	24111	postgres ts_rank_cd: no function matches the given name and argument type	select title, ts_rank_cd(to_tsvector(title), query) as rank from food.usda, to_tsquery('egg') query where to_tsvector(title) @@ query order by rank desc 	0.0212952779758483
18309971	20061	how to merge multiple tables in mysql	select t1.id,t1.name,t2.sex,t2.address   from  (select *,@row1 := @row1 + 1 as rownum   from table1   join (select @row1 := 0) r) as t1 join (select *,@row2 := @row2 + 1 as rownum   from table2   join (select @row2 := 0) r) as t2 where t1.rownum = t2.rownum 	0.00984572663649715
18312429	40815	how to create/add a column in sql select query based on another column values	select hook_type,     case hook_type       when 0 then 'offer'       when 1 then 'accept'       when 2 then 'expired'    end as hook_name,    count(*) as number_of_exchange_activities  from `exchange`  group by hook_type 	0
18313564	8029	sql select ... where in with separate limit,offset clause	select * from (     select *,         row_number() over(             partition by user_id             order by createdat desc, rating desc         ) as rn     from t1      where         status = 1 and some_field not in (?, ?, ..., ?)         and user_id in (1,2,3) ) s where rn <= 10 order by user_id, rn 	0.649530677233462
18315310	20205	multiple row totals in ssrs 2005	select ogl.pacostcenter, vpt.ll6, sum((vpt.timeinseconds*1.0)/3600) [hours],        sum(case when vpt.paycodename in ('519-h-overtime 1.0', '519-h-holiday ot 1.5',                                          '519-h-overtime 1.5', '519-h-overtime 2.0'                                         )                 then (vpt.timeinseconds*1.0)/3600                 else 0            end) as overtimehours,        sum(case when vpt.paycodename in ('519-h-regular')                 then (vpt.timeinseconds*1.0)/3600                 else 0            end) as regularhours, from totals as vpt inner join oraclelookup ogl on vpt.ll6 = ogl.oraclecostcenter collate sql_latin1_general_cp1_ci_ai where vpt.date between @startdate and @enddate and vpt.paycodename in ('519-h-overtime 1.0',             '519-h-holiday ot 1.5',             '519-h-overtime 1.5',             '519-h-overtime 2.0',             '519-h-regular') group by ogl.payrollaccount, vpt.ll6 order by  ogl.payrollaccount, vpt.ll6; 	0.0377546652867518
18327356	16303	select rows who's first result is a specific value	select v.users_id   from pageviews v join (   select users_id, min(time_in) time_in     from pageviews    group by users_id ) q on v.users_id = q.users_id and v.time_in = q.time_in  where v.articles_id = 1 	0
18328964	32476	combining a in and and query	select id from testtable where id in (2,3,4)  and  (comment like '%celsius%' or comment like '%farenheit%') 	0.208252665350779
18334819	35905	how to select the exactly wanted rows from 2 tables	select t.*, tu.userid from treatments t left join treatmentusers tu      on t.id = tu.treatmentid      and tu.userid = 1 	0.000194277975921412
18342816	9748	sql query with multiple values iteration like for each	select      d1.ln_id,      max(d1.ln_date) as first_dt,      max(d1_a.ln_date) as last_dt,      max(d2.ln_mod_date) as ln_mod_dt,      max(d2.ln_pymt_date) as ln_pymt_dt   from      detail1 d1     inner join detail2 d2 on d1.ln_id=d2.ln_id     inner join detail1 d1_a on d1_a.ln_id=d1.ln_id where      d1.ln_catg = 16      and d1_a.ln_catg = 16      and d1_a.ln_date < d1.ln_date group by      d1.ln_id 	0.0825711870304904
18343873	4787	sql query into delimited string in stored procedure	select stuff((select (     select  '~' + (         control_number+'|'+         address1 +'|'+         address2 + '|'+         city + '|'+         [states] + '|'+         zip)     from address_tabletype     for xml path(''), type     ).value('text()[1]', 'varchar(max)')), 1, 1, '') 	0.325600903707845
18347375	25705	get total amount of fruits each mammal is carring	select mammal_id, mammal_name, fruit_name, sum(gets) as has from report group by mammal_name, fruit_name 	0
18358490	36568	left join with at least one row with condition from right mysql	select  r.`id`, r.`name`, o.`date`, o.`status`,  o.`id` order_id from    restaurants r         inner join orders o              on r.id = o.restaurant_id             and o.date between '2013-08-10' and '2013-08-31'          inner join         (   select  distinct o2.restaurant_id             from    orders o2             where   o2.date between '2013-08-10' and '2013-08-31'              and     o2.status = 'reserved'         ) o2             on r.id = o2.restaurant_id; 	0.0216057331528713
18362445	39795	mysql auto increment initial value not working	select lpad(id, 5, '0') as padded_id from bids 	0.0260688527936471
18376813	27589	select min, max, avg and current (for latest insert id) value all together	select m.id, price,         round(avg(price)),         min(price),        max(price),        round((avg(price)-min(price))/avg(price) * 100) as differenceinprices  from `m-orbitzone` m inner join (    select    id    from    `m-orbitzone` m    where id = (select max(id) from `m-orbitzone` sm where m.arv = sm.arv and m.date1 = sm.date1 and m.date2 = sm.date2) ) s on m.id = s.id where dep = 'mow'    and returnornot = 1  group by arv, date1, date2  order by differenceinprices desc limit 1000 	0
18387159	1981	sql query - id join, just duplicates	select itemid, datepurchased, customerid from  (    select       t1.itemid, t1.datepurchased, t2.customerid,        count(*) over (partition by t2.customerid) as itemcnt    from table2 t2       join table1 t1 on t1.itemid = t2.itemid  ) dt  where itemcnt > 1 	0.0972498510573139
18393682	2290	mysql select distinct category and list items under that category	select categorytype, group_concat(distinct elements) from t group by categorytype; 	0
18395377	31811	creating stored procedure with 2 different sets of data (using value from first data as parameter for 2nd data)	select     t1.[start], t1.[end], count(*) from table1 as t1     left outer join table2 as t2 on t2.timestamp between t1.[start] and t1.[end] group by t1.[start], t1.[end] 	0
18395624	38982	trunc and timestamp issue	select columns    from table   where recorddate = trunc(:histdate) 	0.55814353985706
18402856	35243	group by clause with min	select distinct on (customer_id) customer_id, id, created_at    from thunderbolt_orders    order by customer_id, id; 	0.723141650718492
18404772	34872	how to return the last record in a table with multiple states	select s1.pk_programstatee, s1.fk_program, s1.state from programstates s1 inner join (   select max(pk_programstate) as mstate, fk_program   from programstates   group by fk_program ) s2 on s2.mstate = s1.pk_programstate and s2.fk_program = s1.fk_program 	0
18412557	22587	return all records of non-given id if just one of those records matches the given id of another field	select * from offers where listing_id in (select listing_id from offers where user_id = 1) 	0
18415003	2318	find equal columns in different tables in mysql	select distinct column_name, count(table_name) as common_count from information_schema.columns where table_name in ('table1', 'table2', 'table3') and table_schema = 'dbname' group by table_schema, column_name having common_count > 1 	0.000144210507098595
18422570	35920	mysql list set theory, relational database	select * from business where not exists(   select 1 from    (        select val from list1   ) x   join   (       select val from list2   ) y   on x.val = y.val ); 	0.252551037456239
18438180	29844	how can i get ot_total and ot_shipping into one row in mysql?	select orders_id,         sum(case when class='ot_shipping' then value else 0 end) as shipping,        sum(case when class='ot_total' then value else 0 end) as total from ot group by orders_id; 	0.000115297575090136
18439409	4106	mysql filling out values from other tables	select v.id, r.title, c.company, l.town, l.country, v.term from  vacancy v join  location l on (v.location = l.id) join   company c on (v.company = c.id) join  role r on (v.role = r.id) 	7.35873368276153e-05
18441577	11059	how to group values of one column based on condition in t-sql?	select v.vra_uid, count(v.visit_uid) as number_of_visits , sum(case when v.visit_cause = 1 then 1 else 0 end) as visits_with_cause_equal_1 from visits v  group by v.vra_uid 	0
18444519	13237	pivot on multiple column sql server	select station as mystation,        sum(case when category = 'category1' then value else 0 end) as category1,        sum(case when category = 'category2' then value else 0 end) as category2,        sum(case when category = 'category3' then value else 0 end) as category3 from (select n.station, t.category,              (case when station = 'station1' then station1                    when station = 'station2' then station2                    when station = 'station3' then station3               end) as value       from t cross join            (select 'station1' as station union all select 'station2' union all select 'station3') n      ) t group by station; 	0.226953674973302
18449195	23336	how to get the cumulative column from my sales table?	select t1.*, sum(t2.amount) from table1 t1 inner join table1 t2 on t1.pid = t2.pid and t1.month >= t2.month group by t1.pid, t1.month, t1.amount 	0
18450287	10829	most recent child record keyed	select mopactivity.mopid, max(mopnotes.mopnotedate) from mopuser.mopactivity  inner join mopuser.mopnotes    on mopactivity.mopid=mopnotes.mopid where mopactivity.mopend between trunc(sysdate-1) + interval '12:00' hour to minute and trunc(sysdate) + interval '9:00' hour to minute and upper(mopactivity.mopstatus) = 'complete' and upper(mopactivity.mopnotificationsent) like '%true%' group by mopactivity.mopid order by mopactivity.mopid 	0
18451390	16685	how do i write a query to return a string concatenated with the greatest number?	select username from table_name order by convert(replace(username, 'prefix', ''), signed) desc limit 1 	0.000676737405672115
18451771	16485	how do i multiply an unsigned int by -1 on a select?	select cast( fieldname * -1 as signed ) from ... select convert ( fieldname * -1, signed ) from ... 	0.0139455804584609
18454316	35342	sql - getting only a particular date for each record	select s.*,        max(f.date) as mostrecentdate,        substring_index(group_concat(form order by date desc), ',', 1) as mostrecentform from student s join      form f      on s.studentid = f.studentid group by s.studentid; 	0
18464846	7740	postgres - finding unique users which have specific records	select user_id from table_user_flags where flag in (1,2) group by user_id having count(distinct flag)=2; 	0
18481197	12763	selecting only top result from two table query	select songs.songdeviceid, count(*) from votes inner join songs on votes.     songid =  songs.songid group by votes.songid, songs.songdeviceid order by count(*)      desc limit 1 	0
18486220	4612	fetching multiple data with sql query	select rf_transaction_id   from transactions_line_detail  where ch_line_code in ('x', 'y', 'z')  group by rf_transaction_id having count(1) = 3 	0.213405694739189
18503172	39880	sql query to group records	select t.client, t.riccode, t.tradedate, count(t.flow) as cnt  from  (     select a.client, a.riccode, a.tradedate, a.flow     from trades a      inner join trades b on a.client = b.client and a.riccode = b.riccode and a.tradedate = b.tradedate and a.flow <> b.flow     group by a.client, a.riccode, a.tradedate, a.flow ) as t  group by client, riccode, tradedate; 	0.0783251903293332
18505826	38704	sql union all statement	select * from (         select 'transfer in' as movementtype, * from vhris_staffmovement_transferin          union all         select 'terminate' as movementtyep, * from vhris_staffmovement_terminate           union all         select 'new hire' as movementtyep, * from vhris_staffmovement_newhire          union all         select 'transfer out' as movementtype, * from vhris_staffmovement_transferout ) as a where cur_deptid in (1,2,3,4,5)         and cast(effectivedate as date) <='2013-08-02'         and cast(effectivedate as date) >= '2012-08-01'         and stafftype in (1,2,3,4,5) 	0.260947763189553
18506973	19743	sql multiple where and fields	select count(m.meet_id), sum(case when m.meet_category = 'long' then 1 else 0 end), sum(case when m.meet_category = 'short' then 1 else 0 end) from meetings m where  meet_id in      (select meet_id     from orders o     where o.order_date >= '2011-03-01'); 	0.163479003252438
18508422	537	how to find a table having a specific column in postgresql	select c.relname from pg_class as c     inner join pg_attribute as a on a.attrelid = c.oid where a.attname = <column name> and c.relkind = 'r' 	0.000405346412170297
18512825	33250	how to sum the column and get the rows based on month and year	select a.userid,   a.points_sum_m as currentmonthpoints,   b.points_sum_y as currentyearpoints from (select userid, sum(points) as points_sum_m    from tbl_points    where month(date) = month(getdate())    group by userid) a inner join (select userid, sum(points) as points_sum_y    from tbl_points    where year(date) = year(getdate())    group by userid) b on a.userid = b.userid; 	0
18514667	10383	how can i change the results of a field in a sql query to only include characters up to the first underscore?	select substring(no_item, 1, charindex('_', no_item + '_')) as no_item,     label, from table 	5.20581697488481e-05
18516444	19285	get minutes since last inserted row	select timestampdiff(minute,posted,now()) as minutes_since_post from blog_comments where article_id = 1023 and commenter_id = 2322 	0
18520178	38142	date conversion in postgress	select to_char(the_date_column, 'mm/yy') from the_table; 	0.186852538167934
18526886	17535	how to show total weekly count in one table	select t1.august, t1.[count],  case datepart(weekday, o.order_date)     when 1 then (select convert(varchar(10), sum(t2.[count]) from tablename t2 where t2.august between dateadd(d,-7,t1.august) and t1.august))     else '' end as weekly_count from tabllename t1 order by t.august 	0
18535934	8674	how to select 2 tbls but only 1 row from second tbl with lowest pk in mysql?	select min(b.img_id), a.car_id, a.make, a.model, a.year, b.img_link  from cars a  left join imgs b on a.car_id = b.car_id  group by a.car_id, a.make, a.model, a.year ; 	0
18538083	34384	filter date to be greater than 24 months rather than 2 years?	select listkey from closing_list where closedate > dateadd(month, -24, getdate()) 	0
18558053	19188	mysql - warranty expired?	select   * from   items where   now() > (invoice_date + interval warranty_period year) 	0.251730955049859
18567574	31988	select within a select based on results mysql	select artist,title, count(*) from table1 group by artist,title 	0.00164649155788256
18568663	202	how to get price in high to low order	select * from product_tb where sub_id='"+bl.sub_id+"' order by cast(price as int) desc 	0.00167708676888484
18584046	23431	use the result from a query table into another query	select (     select sum(`total_amount`)     from `civicrm_contribution`     where `contact_id` in (select `id` from `civicrm_contact` where `first_name` like 'test2' ) as contact_id)  ) - (     select sum(`fee_amount`)     from `civicrm_participant`     where `contact_id` in (select `id` from `civicrm_contact` where `first_name` like 'test2' ) as contact_id) ) as remainingpoints 	0.000825904087111219
18588882	31149	set a column value to a subquery result	select distinct clientid, eventtype, eventdescription,                 substring(eventtime, 0, 12) as eventtime                            from         eventlog where     (eventtype = 'gig') 	0.00849290169585712
18604251	38200	sql query : how to aggregate on part of date	select     oi.product_name,     sum(iif(month(o.order_date) = 1, oi.items_purchased_count, 0)) as jan,     sum(iif(month(o.order_date) = 2, oi.items_purchased_count, 0)) as feb,     ... from orders o inner join order_items oi on o.order_id = oi.order_id group by oi.product_name 	0.045059633125256
18629991	7840	compare 2 tables for changes in each columns	select *  from table1 full outer join table2 on table1.id = table2.id where table1.col1 <> table2.col1 or table1.col2 <> table2.col2 or table1.col3 <> table2.col3 ... 	0
18631795	16190	sql query - find missing info	select uw.* from      (         select [user], [week]         from users             inner join weeks on users.startweek<=weeks.[week]     ) uw         left join      submissions         on uw.[user]= submissions.[user]         and uw.[week] = submissions.[week]         and submissions.[status]='complete' where submissions.[user] is null 	0.0285972655556347
18634537	33449	how to pass a integer array to not in conditions in postgresql?	select fields from table where fieldno <> all(xfields); 	0.250044038186747
18638460	32763	mysql query ordering in join tables	select doc.code,doc.dataaccept,doctypes.name,org.name from doc left outer join doctypes join org on doc.type=doctypes.code and doc.org=org.code; where doc.code < 1000 ; order by 1 	0.572800468974092
18658599	39369	sql n:m relation	select      s.id  as studio_id,      e.id  as equipment_id,      se.id as studio_equipment_id from       studios as s   cross join       equipment as e   left join       studio_equipment as se         on  se.studio_id = s.id        and se.equipment_id = e.id ; 	0.770062564230508
18659638	27243	select all but rows which match across two tables in query	select *   from events e   left   join seen s     on s.event_id = e.id)    and s.user_id=34  where e.meta_id in (45,37,43)    and s.event_id is null  group      by e.event_id  order      by e.date desc 	0
18659839	12714	select query with cross rows where statement	select t1.someid from yourtable t1 where t1.number in (10,14,11) group by t1.someid having count(distinct t1.id) = (select count(distinct t2.id) from yourtable t2 where t1.someid=t2.someid) 	0.662594858809662
18682873	29786	identify the period start date for each day in a range of dates	select     emp, salesdate, sales, prevperiod, item,     dateadd(day, -datediff(day, '20120910', salesdate) % 14, salesdate) as salesdateperiodstart1,     dateadd(day, (datediff(day, '20120910', salesdate) / 14) * 14, '20120910') as salesdateperiodstart2 from table1 	0
18716716	39037	select query with sum	select studentname,        sum(subjectmark) from   table_name group  by studentid,           studentname 	0.309922457600456
18721678	5516	"join" admins of different tables into a string	select id, name, topic, group_concat(owner_admin) from (     select id, name, topic, owner owner_admin from rooms     union     select id, name, topic, account_id from rooms     left join room_admins on id = room_id ) s where name like "%htm%" or topic like "%htm%" group by id, name, topic 	0.000905447018598999
18733876	4744	select one column multiple time	select test, 'rent1' from tablea where conda union select test, 'rent2' from tablea where condb 	0.00195129920059776
18745977	31813	dot product in an sql table with many columns	select t.*,        (t.col0 * garden.col0 +         t.col1 * garden.col1 + . . .         t.col999 * garden.col999        ) as dot from t cross join      (select t.*       from t       where name = 'garden'      ) garden; 	0.0116582566592735
18746771	16088	multiple joins and where conditions all together	select     * from     table1 as t1     inner join table2 as t2 on t1.a3 = t2.b3     inner join table3 as t3 on t2.b3 = t3.c3     inner join table4 as t4 on t3.c3 = t4.d3 where         t1.a1 between '2013-09-13' and '2013-09-14'     and t1.a2 = '2'     and t4.d3 in (1, 2, 3, 4) 	0.176974864981267
18759360	25773	merge two pivots in sql server 2008	select emp.*, late.islate from (     select *     from (         select empid, daystatus         from attendance         where _date >= '08/01/2013' and _date <= '08/31/2013'      ) m     pivot (         count(daystatus)         for daystatus in ([p], [ph], [a])     ) ) emp join      (select *     from (         select empid, islate         from attendance         where _date >= '08/01/2013' and _date <= '08/31/2013'      ) m     pivot (         count(islate)         for islate in ([1])     ) n ) late on emp.empid = late.empid 	0.349985945464761
18761166	18087	count of columns in temp table in sql server	select count(*) from tempdb.sys.columns where object_id = object_id('tempdb..#mytemptable') 	0.005191124324415
18767015	29892	turn mysql key pair into concatenated list	select   businesses.name,   group_concat(categories.name) as all_categories from   businesses     left join business_categories       on businesses.id=business_categories.business_id     left join categories       on business_categories.category_id=categories.id group by   businessess.name 	0.000145945906732641
18776607	33097	is it possible to order "first n" records randomly with only one select?	select name, view_count  from `ex`.`item`  where status='available'  order by rand(), view_count asc limit 40; 	0
18776975	36721	sql select names like $name but not exact same name twice	select custname, date, id  from booking b inner join (     select max(date) maxdate, custname     from booking     where custname like '%$s%'     group by custname ) bm   on b.custname = bm.custname   and b.date = bm.maxdate where custname like '%$s%' order by b.date desc 	0.00159652313816948
18780539	32426	how to get last 20 min active records from a table which is having user login date with time	select distinct userid from your_table where logintime >= dateadd(minute, -20, current_timestamp) 	0
18796096	6757	mysql specific group by	select name, min(time), max(time) from ( select name,  time, @group_num := if(@name != name, @group_num + 1, @group_num) as group_number, @name := name from yourtable , (select @group_num := 1, @name := null) variables order by id ) sq group by group_number 	0.0831346365153613
18834799	40980	how to count id numbers separated by a comma from one cell	select length(product_id) - length(replace(product_id, ',', ''))+1 as counts from table1 	0
18837077	12198	sql query select with ranges	select     city,     sum(money),     sum(case when age < 30 then 1 else 0 end),     sum(case when age > 30 then 1 else 0 end) from     table group by     city 	0.102965051518672
18838657	10909	count on join table	select p.productid , p.productdesc, count(p.productid) from product p inner join orderdetails od on p.productid = od.productid inner join order1 o on o.orderid = od.orderid where orderpayment = 'cash' group by p.productid, p.productdesc 	0.0799367387626189
18857706	2470	mysql like and different value not working	select users . * , image_upload.name_image from users left join image_upload on users.profile_image = image_upload.id_image where users.id <>1 and (lower( users.name ) like  'f%' or lower( users.surname ) like  'f%') limit 5 	0.600361567612201
18862004	39075	sql query to filter a table using another table	select * from datatable where id in (   select dt.id   from datatable dt     join filtertable ft on ft.name = dt.name            and ft.value = dt.value   group by dt.id   having count(*) = (select count(*) from filtertable) ) 	0.00590128839583362
18863604	40348	sql sum sub-query with joined tables?	select g.gemid as ggemid, g.title as gtitle, gemdetail.filename as gfilename, r.filename as rfilename, rt.sum_rating from (select gems.* from gems ) g  left join  (select title, x.gemid, x.replygemid, x.userid, y.filename  from gems x  left join gemdetail y on x.gemid = y.gemid ) r on g.gemid = r.replygemid  left join gemdetail on g.gemid = gemdetail.gemid  left join (select gemid, sum(rating) as sum_rating from rating group by gemid) rt on g.gemid = rt.gemid 	0.177215626158711
18864200	19431	coldfusion query database to get the closest number	select top 1 * from [calculator_data]  where qty < 61000 order by qty desc 	0.00417420077162142
18869232	6125	how to create in view new row after each next row	select  ...    case when x = 1 then col else your calculation end from table cross join (select 1 as x union all select 2 as x) dt 	0
18869665	16523	query with sum and count in 2 tables	select  a.id_user,         a.point + (count(b.id_point_extra) * ?) totalpoints from    points a         left join points_extra b             on a.id_user = b.id_user group   by a.id_user 	0.0258576913551672
18876546	29711	self-pointing foreign key query names not ids	select  et1.id,         et1.name,         et2.name as parentname from    dbo.entitytype et1 join dbo.entitytype et2 on et1.parenttypeid = et2.id 	0.000150121739716149
18889467	24667	average values of all weeks	select yearweek(`time`), avg(value)  from table  where time between date_sub(now(), interval 8 day) and now() group by yearweek(`time`) 	0
18905455	15485	sql modifying rows based upon value in previous rows	select id,        (select top 1 name         from yourtable t2         where t2.id <= t.id and               t2.name is not null         order by t2.id desc        ) as name from yourtable t; 	0
18905533	11402	mysql movie database	select distinct m.title,              group_concat(distinct g.genre) as genres,              group_concat(distinct f.format) as formats from movies m  left join moviegenres mg on m.code=mg.moviecode left join genres g on mg.gencode=g.code left join movieformats mf on m.code=mf.moviecode left join formats f on mf.formcode=f.code group by m.code; 	0.30150788832565
18906606	13072	sql: grouping tables with many-to-many relations	select table1.user_id, table1.id, q.max_date from table1 inner join  (select id, max(date_) as max_date from table2 group by id) as q on table1.id = q.id 	0.302305341724951
18907935	37155	select sql from table 1 then filter table 2 clolumn with table 1 column condition	select * from table2 as t2 inner join (select * from table1 where groupid=1) as t1 on t1.itm_id =t2.itm_id where t2.price_id=200 	0
18919802	20000	return single record where multiple linked records exist in mysql	select   reviews.review_id   reviews.review_id,   reviews.poi_id,   reviews.review,   poi.name,   select (     images.file     from images      where reviews.poi_id = images.id     order by images.id asc     limit 1   ) from   reviews join poi on reviews.poi_id = poi.id order by   poi.name; 	0.000218994362365219
18925768	9641	how do you query in sqlite3 with foreign keys and different tables?	select m.mid, m.title, m.releasedate    from directed dir, director d, movie m where d.name = 'ang lee' and d.did = dir.directorid and dir.movieid = m.mid 	0.00148717179646411
18933425	27399	mysql join/sum/sort	select  a.id, sum(b.stars) totalrating from    profiles a         inner join ratings b                 on a.id = b.profileid group   by a.id order   by totalrating desc limit   5 	0.327086913543303
18936963	7133	sql query count return zero with multiple tables join	select     r.regioncode,     c.classcode,     count(cf.id) as frequency  from     region r         cross join     class c         left outer join     owner o         on r.areacode = o.areacode         left outer join     cf         on o.cf_id = cf.id and            c.cf_id = cf.id group by     c.classcode,     r.regioncode order by     r.regioncode,     c.classcode 	0.104882876208392
18953788	30770	position of a column in a table	select ordinal_position from information_schema.columns where table_name = 'yourtablename' and column_name = 'yourcolumnname' 	0.00147971881374886
18961398	20747	selecting columns using variables	select u.town l.userid, l.type  from listings l inner join users u on u.userid = l.userid    where l.type = '{$type}'  and u.town = '{$town}' 	0.0131027455135967
18965122	30274	select, join, and a where != statement returning too many rows	select s.songname, s.userid, s.songid from song s left join linker l on s.songid = l.songid and l.catid = 155 where s.userid = 2 and l.id is null 	0.730954639671541
18977060	9795	how to change the value of a query returning true/false	select case when md.seen_doctor = 'false'              then 'did not seek medical attention'             else 'did seek medical attention'        end as res_checkbox from your_table 	0.00227155312540039
18987071	32511	tsql find missing values	select tablea.*, bprev.sales from tablea left outer join tableb    on  tablea.cmp_code = tableb.cmp_code    and tablea.[year]   = tableb.[year]    and tablea.[week]   = tableb.[week] left outer join tableb as bprev    on  tablea.cmp_code = bprev.cmp_code    and tablea.[year]   = bprev.[year]+1    and tablea.[week]   = bprev.[week] where tableb.cmp_code is null 	0.0185771890196859
19008173	37777	sql command to display highest repeated field in a column	select chairman from mytable group by chairman having count(*) = ( select top 1 count(*) from mytable group by chairman order by count(*) desc) 	0
19008697	3759	sum items in a join statement mysql	select huxwz_user_orders.*, huxwz_users.name, huxwz_users.email, huxwz_users.id, sum(huxwz_user_orderitems.price) from huxwz_user_orders left outer join huxwz_users on (     huxwz_user_orders.userid = huxwz_users.id ) left outer join huxwz_user_orderitems on (     huxwz_user_orders.id = huxwz_user_orderitems.orderid ) group by huxwz_user_orderitems.orderid order by huxwz_user_orders.id 	0.109954294235056
19025112	34468	mysql with all and blank counts	select `emp_dept`,  count(*) as 'dept_count',  sum(if(`emp_assessment_data` = '', 1, 0)) as 'blank_emp_assessment_count'  from `employee_master` group by `emp_dept` 	0.0175698753374615
19066075	35396	how to join many to many relationship on max value for relationship field	select     s.shop_name,     i.item_name,     si.price from     sells_table si join     shop_table s on     si.shop_id = s.shop_id join     item_table i on     si.item_id = i.item_id where     (shop_id, price) in (         select             shop_id,             max(price) as price_max         from             sells_table         group by             shop_id     ); 	0.000599785449065352
19076166	34823	sql - 'partial' group by, different behavior for different columns	select     t1.product_id, t1.person_id,     t1.person_address,     group_concat(t2.person_address) as other_address from table1 as t1     left outer join table1 as t2 on         t2.product_id = t1.product_id and t2.person_id <> t1.person_id where t1.person_type = 0 group by t1.product_id, t1.person_id 	0.00424193269592836
19087663	15322	mysql query items with the largest price increase	select   today.resource_id,  (today.avg_price - yesterday.avg_price) / yesterday.avg_price as percent_increase from  item_prices today,  item_prices yesterday where today.resource_id = yesterday_resource_id and   date(from_unixtime(today.timestamp)) = $today and   date(from_unixtime(yesterday.timestamp)) = $yesterday order by percent_increase desc  limit 10 	0.00119668099161704
19089013	16455	sql select max(count)	select "name", count(*) maximum from "users"     inner join "microposts" on "microposts"."user_id" = "users"."id"  group by users.id  order by maximum desc  limit 1 	0.790419419134049
19090094	14047	php work out age in years and months from timestamp	select         timestampdiff(year,concat(dob_year, '-', dob_month, '-', dob_day),curdate())        as          years,          (timestampdiff(month,concat(dob_year, '-', dob_month, '-', dob_day),curdate()) -          timestampdiff(year,concat(dob_year, '-', dob_month, '-', dob_day),curdate())*12)        as          months        from          members 	0.000233946018859474
19091569	2595	creating a view with sums from multiple tables (oracle sql)	select v.fname, sum((r.price*b.bookingdays)+nvl(bso.cost,0))   from visitors v    join bookings b     on v.visitorid = b.visitorid   join rooms r     on b.roomno = r.roomno   left outer join (select bs.bookingid,sum(cost) as cost                       from booking_services bs                      join services s                        on s.serviceid = bs.serviceid                     group by bs.bookingid) bso     on bso.bookingid = b.bookingid group by v.fname; 	0.0681840824266677
19092893	483	concatenating columns with sql	select id,group_concat(name separator '-') as name from table group by id 	0.0448422139019386
19100772	35106	how to get average of the 'middle' values in a group?	select group_id,        avg( test_value ) from (   select t.*,          row_number() over (partition by group_id order by test_value ) rn,          count(*) over (partition by group_id  ) cnt   from test t ) alias  where     cnt <= 3    or     rn between floor( cnt / 2 )-1 and ceil( cnt/ 2 ) +1 group by group_id ; 	0
19112876	18829	how to calculate multiple aggregates on multiple columns	select avg(column1) as avg_resp,    avg(col2) as ncount,    max(column1) as max_col1,    max(col2) as max_col2,    min(column1) as min_col1,    min(col2) as min_col2   from table 	0.00250993740803208
19114748	39245	sql query taking time, as i am looking into three tables	select     ee_expert.expert_id ,     avg( ee_expert_rating.rating_stars ) as total_rating,     count( distinct ee_expert_rating.rating_id ) as rating_count from     ee_expert_rating right join     ee_expert on ee_expert.expert_id = ee_expert_rating.expert_id where     expert_verified_email =2 and               expert_brief_description != '' and         expert_account_status =1 and               exists(                                        select                                         expert_id                              from                                           ee_expert_categories         where             ee_expert_categories.category_id =5 and             ee_expert_categories.expert_id=ee_expert.expert_id     ) group by     ee_expert.expert_id order by     rating_count desc 	0.481522014903413
19129660	28636	microsoft access query top 50% and last 50% values	select *  from table where tableid not in (     select top (         (select count(*) from table) - 700000     ) tableid     from table ) 	0.00776554727346075
19132543	9775	split/extract values from record-type single column, apply user-defined function to multiple-row cte	select (myfunc(arg)).* from rows; 	0.0508968229091093
19137969	26714	how to use sql reserve keyword in column name	select [desc] from tablename 	0.313864436870883
19151115	2492	date time differences calculation in oracle	select extract(day                from diff) days,        extract(hour                from diff) hours,        extract(minute                from diff) minutes,        extract(second                from diff) seconds,        extract(year                from diff) years from   (select (cast (to_date(t.column1, 'yyyy-mm-dd hh:mi:ss') as timestamp) -cast (to_date(t.column2, 'yyyy-mm-dd hh:mi:ss') as timestamp)) diff    from tablename as t) 	0.0137526783532647
19153884	36913	ms sql server: cast double to string and compare text	select * from mytable where cast(id as varchar) like '21%' 	0.545892809386153
19155552	41150	mysql query for matching array of strings with database	select * from sometable cross join (     select max(if(find_in_set(id_1, replace("a b", " ", ",")) > 0, 1, 0) + if(find_in_set(id_2, replace("a b", " ", ",")) > 0, 1, 0) + if(find_in_set(id_3, replace("a b", " ", ",")) > 0 > 0, 1, 0)) as maxcount     from sometable     where find_in_set(id_1, replace("a b", " ", ",")) > 0     or find_in_set(id_2, replace("a b", " ", ",")) > 0     or find_in_set(id_3, replace("a b", " ", ",")) > 0 ) sub1 where if(find_in_set(sometable.id_1, replace("a b", " ", ",")) > 0, 1, 0) + if(find_in_set(sometable.id_2, replace("a b", " ", ",")) > 0, 1, 0) + if(find_in_set(sometable.id_3, replace("a b", " ", ",")) > 0 > 0, 1, 0) = sub1.maxcount 	0.0138059122136634
19156723	17583	how can i retrive the top 3 rated events mysql	select e.event_id, event_name, avg_rating from event_table e join (     select event_id, max((organization+value_for_money+fun_factor+facilities)/4) avg_rating     from ratings_table     group by event_id     order by avg_rating desc     limit 3) r on e.event_id = r.event_id 	0.000561615890269267
19158409	6072	sql equivalent of countif() across 2 columns	select id       ,current       ,nxt       ,nvl2(nxt,decode(next,lead(current) over (partition by id order by id),1,0),0) occured   from yourtable 	0.0339772189816994
19163219	8071	select records in on table based on conditions from another table?	select * from b where type_id in (   select type_id   from a   where status = true ) 	0
19165213	8759	how to query for xml values and attributes from table in sql server?	select     s.sqmid,     m.c.value('@id', 'varchar(max)') as id,     m.c.value('@type', 'varchar(max)') as type,     m.c.value('@unit', 'varchar(max)') as unit,     m.c.value('@sum', 'varchar(max)') as [sum],     m.c.value('@count', 'varchar(max)') as [count],     m.c.value('@minvalue', 'varchar(max)') as minvalue,     m.c.value('@maxvalue', 'varchar(max)') as maxvalue,     m.c.value('.', 'nvarchar(max)') as value,     m.c.value('(text())[1]', 'nvarchar(max)') as value2 from sqm as s     outer apply s.data.nodes('sqm/metrics/metric') as m(c) 	0.00231828691479951
19173687	34358	mysql between clause inside case when statement and count number of items in column	select      sum(lcd) lcdcnt,     sum(led) ledcnt,     sum(3d) 3dcnt,     sum(hd) hdnt,     sum(fullhd) fullhdcnt,     sum(3d) 3dcnt,     sum(case when displaysize between 1  and 32 then 1 else 0 end) as dispcntlessthan32,     sum(case when displaysize between 33 and 42 then 1 else 0 end) as displaycntbetween32and42 from table1 where brandid = 3 	0.0435605751658326
19173827	14835	how to merge data from different column when data is not null?	select concat_ws(' ',           coalesce(concat('name: ', what_is_your_name), ''),          coalesce(concat('age: ', how_old_are_you), ''),          coalesce(concat('occupation: ', your_occupation), '')) survey_details   from survey 	0.000350106327687631
19177038	36887	create an sql query to retrieve elements between 2 dates t1 and t2 or outside t1 and t2	select *  from mytable  where (tmp between t1 and t2) or ((tmp < t1 or tmp > t2) and (tmp not between t1 and t2)) 	5.48981693311999e-05
19181773	3870	current time and date	select column1,         column2,        date_format(date_column, '%d-%m-%y %h:%i') as formatted_date,        othercolumn from blogposts 	0.000827208913773192
19194470	38494	only getting first letter of only first column in database	select left(`name`, 1) as first_letter_name,        left(`second_col`, 1) as first_col2,        left(third_col, 1) as first_letter_col3, from register 	0
19195198	1867	retrieve sum of 5 top score from a table in mysql	select team_id,sum(score_rank) from contest_result_total where (select count(*)       from contest_result_total as c       where c.team_id = contest_result_total.team_id         and contest_result_total.score_rank <= c.score_rank) <= 5 group by team_id 	0
19205730	15518	sql schema help for table with two semi-related join tables	select f.*       ,fr.return_month as fund_return_month       ,fr.return_value as fund_return       ,hml.return_value as hml       ,mkt.return_value as mkt       ,smb.return_value as smb     from fund f     inner join fundreturn fr on f.fund_symbol = fr.fund_symbol     left join factorreturn hml      on f.region_key = hml.region_key     and hml.factor_key = 'hml'     and hml.return_month = fr.return_month     left join factorreturn mkt      on f.region_key = mkt.region_key     and mkt.factor_key = 'mkt'     and mkt.return_month = fr.return_month     left join factorreturn smb      on f.region_key = mkt.region_key     and smb.factor_key = 'smb'     and smb.return_month = fr.return_month     where f.fund_symbol = 'vti'     and fr.return_month between 201001 and 201012     and hml.return_month between 201001 and 201012; 	0.528962774795517
19210876	21098	sql max(datetime) and category filter without group by	select * from (     select datetime, configid, rowid,          row_number() over(partition by configid, rowid order by datetime desc) as rownum     from linkedtabledefinition a     inner join tabledefinition b on a.target = b.id     inner join viewwithinfo c on a.target = c.id ) src where src.rownum = 1 	0.070580911803762
19217923	22475	how to do select count(*) group by and select * at same time?	select t.id, t.value from table t inner join  (   select id, count(*) as cnt    from table    group by id ) x on x.id = t.id order by x.cnt desc 	0.000405989260902989
19217971	16880	rename a selected row in mysql	select 'data lync' as `cf_1573`, sum(counter) as lyncs  from (  select    cf_1573,   count(cf_1573) as counter   from vtiger_purchaseordercf   where cf_1573  in('lync front end (std)','lync front end (ent)','lync backend',     'lync edge','lync sba','lync dns checks','lync certificate checks')  group by cf_1573 ) as mslync 	0.00220341800832588
19222368	17784	finding a unique value from 2 columns and then a ratio of those values	select player1,player2, concat('player',if( (select count(dt.player1) from table as dt where mt.player1 = dt.player1) > 0, player1,player2),':', (select count(dt.player1) from table as dt where mt.player1 = dt.player1), ' / ', (select count(dt.player2) from table as dt where mt.player2 = dt.player2) )   from table mt where player1 != player2 group by palyer1,player2 order by (player1/if(player2 is not null and player2 != 0,player2,1) desc 	0
19227492	971	selecting values from a query that are negative in sybase	select art_ref  from tablename  where semester_num=28  and art_ref <0 	7.92858969013589e-05
19237864	14661	sql having 2 types but no more	select        mt2.carrier,       mt2.networktype,       mt2.count    from       ( select carrier,                sum(case when  network_type in ( 'none', 'wifi_11b_g')                         then 1 else 0 end ) as networksiwant,                count(*) as allnetworksforcarrier            from                mytable            group by                carrier ) prequery       join mytable mt2          on prequery.carrier = mt2.carrier         and mt2.network_type in ( 'none', 'wifi_11b_g')    where           prequery.networksiwant = 2       and prequery.allnetworksforcarrier = 2 	0.0450673118816697
19241658	11481	how can i connect into one collumn all records that have the same id?	select id,group_concat(name separator ' ') from tablename group by id; 	0
19243972	10449	mysql select max value of a pair of column in one query	select * from tablename order by value1 desc, value2 desc limit 1 	0
19244434	11771	how to retrieve records from multiple tables using hql innerjoin	select distinct c.*  from class c  inner join person_talent pt on c.person_id=pt.person_id where pt.personid=1 and pt.persontalentname='hql' 	0.00451005982758078
19250552	29694	add sequence record numbers	select t.id, t.qty,    ((select coalesce(sum(qty),0) from table1 a where a.id < t.id) + 1) as range_begin,   ((select coalesce(sum(qty),0) from table1 a where a.id < t.id) + t.qty) as range_end from table1 t 	0.00141691633535056
19256334	34992	how to compare fields from different tables	select *  from products inner join stock on products.sku = stock.sku where products.minimum_stock > stock.qty; 	5.54763393445642e-05
19270677	25105	check if table exist/created already in bb 10 cascades	select count(*) from sqlite_master where type='table' and name='table_name'; 	0.000547648290840557
19276351	31447	join 3 tables and group	select d.department_name, l.city, count(distinct e.job_id) from employees e join deptos d on (e.department_id=d.department_id) right join locations l on (d.location_id=l.location_id) group by d.department_name, l.city 	0.165458887549594
19283365	15065	daily page ratio mysql query	select date(`date`),        count(`page`) as indexcount,         sum(`page` = 'index.php') as idx_count,         sum(`page` <> 'index.php') as not_idx_count        timestampdiff(day,date,now()) as days from `tracking` group by date(`date`) having days <30 	0.0104207129959205
19291696	29238	convert a varchar to datetime including hour minute and seconds	select cast(replace(substring('29-jul-11 02.44.29.984664000 pm',  0, len('29-jul-11 02.44.29.984664000 pm') - 9),'.',':') as datetime) 	0.000160727266880863
19297668	32971	trying to combine multiple rows from a table into one row	select main.claimnumber,    left(main.serials,len(main.serials)-1) as "serials" from(select distinct t2.claimnumber,         (select t1.serialnumber + ',' as [text()]         from claim t1         where t1.claimnumber = t2.claimnumber         order by t1.claimnumber         for xml path ('')) [serials]  from claim t2) [main] 	0
19306788	5938	sql query with if condition	select id,name  from service  where id not in (select service_id from clients                  where client = whichever_is_currently_logged_in_by_id?) 	0.6445651806648
19324868	6809	sql for randomize posts	select city_id, city_name, city_order from table_name order by rand() 	0.0344513444892258
19334128	35409	selecting distinct value order by desc	select customer_id, max(time) from table_name group by customer_id order by max(time) desc 	0.00657606923633578
19336145	4463	return row(s) if sum of a column reaches to certain number	select * from mybb_reputation group by rid having sum(reputation) = 3 order by rand() limit 1; 	0
19340723	844	getting related items for a chosen item in mysql	select tbl_item.id from tbl_item ti   inner join tbl_item_term_map ttm on ttm.tbl_item_id = ti.id inner join tbl_item_term tt on tt.id = ttm.tbl_item_term_id where tt.terms in (     select tt.terms from tbl_item ti      inner join tbl_item_term_map ttm on ttm.tbl_item_id = ti.id     inner join tbl_item_term tt on tt.id = ttm.tbl_item_term_id     where ti.id = 111;  ); 	5.94532704851626e-05
19342781	22233	create sql query string	select y.s - x.s as sum from (select sum(qtemv) s from mouventdestock where typemv=1 and codemv = 'art_18') y, (select sum(qtemv) s from mouventdestock where typemv=0 and codemv = 'art_18') x; 	0.345441962071886
19345689	36950	mysql - exclude all blocked users from the results	select * from users where user_id <> 4 and language = 'en'     and user_id not in(select blocked_user_id from users_blocked where user_id = 4)     and user_id not in(select user_id from users_blocked where blocked_user_id = 4) 	0.000103528830999246
19352100	1582	google bigquery sql for summing individual columns	select code, count(col_a) count_column_x, count(col_b) count_column_y from [your:list.of_codes] a left join each [your:sample.table] b on a.code=b.col_a group by 1 	0.145423925906418
19354683	6173	how to simplify a query between many to many relationship	select roleid   from role except select roleid   from userrole  where userid = 2 	0.370393052339306
19355536	32086	mysql query next id with parameters	select * from table_name where status = 1 and id > 1 order by id asc limit 1; 	0.0307099062110111
19359006	33029	count() occurences in a separate table	select   m.* , (select count(*) from messageto mt where mt.messageid = m.messageid) as cnt from message m 	0.00137074919027696
19360150	17314	select parent row from same table when a child row is supplied	select parent.name, child.name from your_table child left join your_table parent on child.parent = parent.id where child.id = 3 	0
19362053	35408	sql query - double condition on relational table	select users.* from users where iduser in (   select userlanguage.iduser   from     userlanguage inner join language     on userlanguage.idlanguage = language.idlanguage   where     language.name in ("fr", "en")   group by     userlanguage.iduser   having     count(distinct language.name)=2 ) 	0.510081425030148
19363445	5070	how do i find the last entry in a table, by date	select      rl.[no_], rl.[start date], rl.[availability status] from        [rental line] rl join (     select         no_,         max([start date]) as [laststartdate]     from [rental line] rl1     group by no_ ) x on rl.no_ = x.no_ and rl.[start date] = x.[laststartdate] 	0
19363600	1993	sql server return multiple queries in a single query	select top 1  'text' as type, text from your_table order by date desc union all select top 1  'imagepath', imagepath from your_table order by date desc union all select 'title',  top 1 title from your_table order by date desc 	0.0862642523853007
19365758	31891	how do i store a value from a select statement in a variable in a mysql stored procedure?	select count(barcode) as count into @myvar from movieitems; 	0.0219248115748268
19370683	34638	sql records and count	select      eventstartdate     ,eventtitle     ,eventdesc     ,eventtime     ,count(eventid)over(partition by eventstartdate) as eventcount from groupevents  where eventstartdate = '10/14/2013' group by eventstartdate 	0.0236609049055307
19374082	21586	fetching column data from 3 table with relation table in-between as mediator in mysql	select pid, pro_name, cat_pro.cat_id, cat.cat_name from prod     inner join cat_pro     on (cat_pro.pro_id = prod.pid)     inner join cat     on (cat.cid = cat_pro.cat_id) where pid='2'; 	0.000869753002436164
19375580	8364	mysql join using date between	select   l.count as visitorsstatistics,   r.count as pageviewsstatistics from   (select * from analytics_metrics where metrics='visitorsstatistics') as l   left join   (select * from analytics_metrics where metrics='pageviewsstatistics') as r     on l.date=r.date where   l.date between @fromdate and @tilldate 	0.118129748236984
19379540	11137	how to update the data type of same name multiple columns	select     'alter table  [' + table_schema + '].[' + table_name + '] ' +     'alter column [' + column_name  + '] datetime;'        from information_schema.columns where column_name = 'lastmodifieddate' 	0
19387062	24872	how do i get a date from my database to show, only when certain conditions are met?	select b.* from bug b inner join users u   on b.bfor = u.userid where u.username = '{$_session['myusername']}'   and b.bugdate = '$bdate' 	0
19397364	34749	mysql: summing the latest amounts banked for each category and type	select eb.currency_id, sum(amount) as total  from events e  inner join (    select faction_id, currency_id, max(date) as md    from event_banking eb    inner join events e    on eb.event_id = e.id    group by faction_id, currency_id ) a  on e.date = a.md inner join event_banking eb on e.id = eb.event_id and a.faction_id = eb.faction_id and a.currency_id = eb.currency_id group by currency_id; 	0
19406904	37585	use sql and print the values from two different tables in the result	select          u.*,          po.entity_id from `users` u join `performer_owner` po on po.field_performer_owner_id = u.id where u.uid in (select uid from `users_roles` where rid= 6); 	0
19407848	6901	mysql manytomany show duplicate rows	select pt.id, tmp1.fname, tmp1.lname, tmp1.dob, tmp1.poid from (   select pt.firstname as fname,          pt.lastname as lname,          pt.dob as dob,          ph.physicianorganizationid as poid   from patient pt, physician ph, patientphysician pp   where pt.id = pp.idpatient and ph.id = pp.idphysician   group by fname, lname, dob, poid   having count(*) > 1) as tmp1 join patient as pt on pt.firstname = tmp1.fname and pt.lastname = tmp1.lname and pt.dob = tmp1.dob join patientphysician as pp on pt.id = pp.idpatient join physician as ph on ph.id = pp.idphysician and tmp1.poid = ph.physicianorganizationid order by pt.id; 	0.00156510708084983
19412493	33149	count unique rows in sql server query	select [requestusers].requestid,         [requests].name,         [requests].isbooked,        count(*) as requestcount from   [requestusers]        join [requests]            on [requestusers].requestid = [requests].id where  [requestusers].daterequested >= '10-01-2013'        and [requestusers].daterequested <= '10-16-2013' group by [requestusers].requestid,         [requests].name,         [requests].isbooked 	0.015811995843684
19412768	4219	select row that has max total value sql server	select top 1 with ties c.customername, sum(s.sum) as totalsum from customer c join sales s on s.customerid = c.customerid group by c.customerid, c.customername order by sum(s.sum) desc 	0
19420826	30890	filter data from mysql table between two values	select *     from        tablea     where        substring(name, -7, 3) > 200     and        substring(name, -7, 3) < 999 	0
19428559	21712	select month day year as date in mysql?	select * from mytable where column_month = date_format(current_date, '%c'); 	0
19450090	33133	sql server 2008 - accumulating column	select          (select min(term) from yourtable ) +'-'+term,                (select sum(value) from yourtable  t1 where t1.term<=t.term)     from yourtable t      group by term 	0.730753825411164
19454979	16460	sql server - shows dates within the current month	select * from   table1 where  duedate >= dateadd(month, datediff(month, 0, getdate()), 0)        and duedate < dateadd(month, 1 + datediff(month, 0, getdate()), 0) 	5.95484306846261e-05
19456564	2225	optimizing mysql query for integer range search	select q.* from    ( select csv.*      from csv     where csv.begin < 3338456592      order by csv.begin desc     limit 1   ) as q where 3338456592 < q.end ; 	0.41485645225393
19466827	39491	sql query where records exist except	select      *  from      [table1] inner join [table2]  on [table1].membernum = [table2].membernum left outer join [table3] on      table1.cardid = table3.cardid where      [table1].cardid<>[table2].cardid and (     cast(coalesce(table3.enddate, dateadd(dd,-1,getdate()) as date) <= getdate()     ) 	0.0739758916888761
19472002	22860	coming up with mysql query on multiple tables	select  m.name as mag_name,           n.name as news_paper_name,           c.fromdate,           c.todate   from   collections as c          inner join target as t on          c.targetid = t.targetid          inner join magazine as m on          t.targetid = m.id          inner join newspaper as n on          t.targerid = n.id          inner join analysis as a on          c.collectionid = a.collectionid 	0.18172044172179
19478482	18756	mysql how to get two results with one query from different tables	select books.book_title, authors.author_name, comments.comment from books inner join books_authors on books.book_id=books_authors.book_id inner join authors on books_authors.author_id=authors.author_id left join comments_users on comments_users.book_id = books.book_id inner join comments on comments_users.comment_id = comments.comment_id inner join users on comments_users.user_id = users.user_id where books.book_id=7 	0
19478489	11473	sql- using a value in one tuple to get a value from another one	select employee.fname, employee.salary, supervisorlist.fname as supervisor  from employee  left join employee as supervisorlist on supervisorlist.ssn = employee.supervisorssn where employee.departmentname='research'; 	0
19482126	9526	mysql join to exclude missing entries	select d.*,t.id from `donations` d left outer join `teams` t on d.teamid = t.id  where t.id is null 	0.00383598970557302
19495427	22813	sql select everything after a certain character	select substring_index(supplier_reference,'=',-1) from ps_product; 	0.00342435536394029
19497512	34207	join tables with different colums to single colum	select b.*      , u.username name      , f.username following   from ignite_board b   join user_info u     on u.id = b.uid    join user_info f     on f.id = b.following   where bnumber = 3   order      by position; 	0.000627273064140296
19498961	31711	sql query, return value from table with no common key	select transactions.postdate, transactions.trankey, transactions.custkey, fiscper from transactions  inner join fiscalperiod on (postdate between startdate and enddate) 	0
19500034	37862	compound foreign keys	select     fk.constraint_name     , fk.table_name fk_table     , kcu.column_name fk_column     , ptc.table_name pk_table     , ptkcu.column_name pk_column     , kcu.ordinal_position from     information_schema.referential_constraints rc     inner join information_schema.table_constraints fk      on rc.constraint_name = fk.constraint_name     inner join information_schema.table_constraints pk      on rc.unique_constraint_name = pk.constraint_name     inner join information_schema.key_column_usage kcu      on rc.constraint_name = kcu.constraint_name     inner join information_schema.table_constraints ptc      on pk.table_name = ptc.table_name       and ptc.constraint_type = 'primary key'     inner join information_schema.key_column_usage ptkcu      on ptc.constraint_name = ptkcu.constraint_name         and kcu.ordinal_position = ptkcu.ordinal_position 	0.0213370156009066
19501769	32070	mysql select row and join to multiple records	select user_id,name,group_concat(value separator ',')as field from users u join fields f  on u.user_id=f.unser_id group by user_id 	0.00268611297698552
19506464	16480	get count of id for name-value pair when name doesn't exist	select count(id) from table where id not in (select id from table where name = 'type') group by id 	0.000669628726306382
19515677	11008	mysql separate and select values from one value field	select id,substring_index(`value`, ':', 1) as valuea , substring_index(substring_index(value,':',2),':',-1) as valueb ,  substring_index(substring_index(value,':',-2),':',-1) as valuec  from   tablename; 	0
19521344	4241	finding smallest value in postgresql	select classcode, grnr, count(uname) as students_in_group from classstud where grnr is not null and sem like '2013-2' group by classcode, grnr order by count(uname) limit 1 	0.00341089277465766
19532296	40593	displaying count of item in one table and all it's columns in another	select p.p_inv,        p.p_name,        p.p_price,        s.s_num,        s.s_in_stock,        count(select * from product p,stock s where p.p_inv=s.s_inv)  as rows_count  from product p  join stock s on p.p_inv=s.s_inv  order by p.s_inv; 	0
19535136	3392	select from table where lastupdated = most recently updated	select * from  'table' order by lastupdated desc limit 1 	0.000191754865070431
19537199	37243	access/sql: multiple conditions on same column	select     p1.nr_pickl,    sum(iif(left(p1.platz_von, 2) = "03", 1, 0) as gang_03,    sum(iif(left(p1.platz_von, 2) = "04", 1, 0) as gang_04,    sum(iif(left(p1.platz_von, 2) = "05", 1, 0) as gang_05 from    pickauf_0110 as p1 group by p1.nr_pickl 	0.0103628940558051
19548653	1256	is it possible to left join two tables and have the right table supply each row no more than once?	select a.id a_id, a.age a_age, a.education a_e, b.id b_id, b.age b_age, b.education b_e from a left join ( select      a.id a_id, min(b.id) b_id from a,b where    abs(a.age - b.age) <= 2 and    abs(a.education - b.education) <= 2   group by a.id ) g on a.id = g.a_id left join b on b.id = g.b_id; 	0
19551755	19838	combining the results of two queries with identical columns into a single result set	select * from (select top 10 tbldata.* from    tbldata where   pk <= 5481 and dev_id = 'rec1' and code_id = 'fmu' and     cast(event_date_time as date) = '10/18/2013' union select  top 10 tbldata.* from    tbldata where   pk >= 5481 and dev_id = 'rec1' and code_id = 'fmu' and     cast(event_date_time as date) = '10/18/2013') a order by pk asc 	0
19554790	19338	is there a less verbose sql query for matching two values against a single list of possibilities?	select    person_per.per_id  from    person_per  left join    person_custom  on    person_custom.per_id=person_per.per_id  where    per_city in ('cathedral city','coachella', 'city1', 'city2', ...) or    work_city in ('cathedral city','coachella', 'city1', 'city2', ...) 	7.04090693165628e-05
19554956	21673	sql server 2012 collapse / unpivot two columns into one?	select u.allnum,        u.metakey from @orig as o   unpivot (allnum for col in (o.num1, o.num2)) as u 	0.0111742372024881
19560614	19351	how to get new clients by months in sql server	select count(*) as new_count,   month(da_reg) as month,year(da_reg) as year   (select count(*) from tbl a where tbl.da_reg>=a.da_reg) as total_cus   from tbl   group by month(da_reg),year(da_reg) 	0.00102960886423499
19570026	24986	mysql, inner join in multiple columns with the same name	select data.col_1, c1.col_1, c2.col_1, data.col_4 from data inner join catalog c1 on data.col_2 = c1.id inner join catalog c2 on data.col_3 = c2.id 	0.00813895132717215
19579813	26750	include null as 0 in count sql query	select p.*, ifnull(l.total, 0) as total from palette p left join (     select palette_id, count(*) as total     from likes     group by palette_id ) l on l.palette_id = p.palette_id order by total 	0.404349268182743
19580094	1997	oracle sql - joining list of values to a field with those values concatenated	select * from tablea a where exists(    select 1 from tableb b    where           ','|| trim( trim( both '*' from a.modifier )) ||','        like  '%,'|| b.mod || ',%' ); 	0
19591007	12311	sql multicolumn index	select * from a where columna > columnb 	0.698223689582016
19594134	37933	fetching parent and child nodes along with counts	select parent.category_id as pid, parent.name as pname, sum(product.product_id is not null) from nested_category as parent, nested_category as midpoint, nested_category as node left join product on product.category_id=node.category_id where (node.lft between parent.lft and parent.rgt) and (node.lft between midpoint.lft and midpoint.rgt) and midpoint.name='televisions' group by parent.category_id order by parent.category_id; 	0.000143133584020879
19606086	10990	total number of months (count) between 2 dates	select datediff(month, createddate, getdate()) from customers 	0
19641285	787	mysql sub select multiple condition	select usr_username as 'user name'   ,count(ad.app_uid) as 'total'   ,sum(case when ad.tas_uid = '23423423455' then 1 else 0 end) as 'total for task a' from app_delegation as ad   join users as u    on ad.usr_uid = u.usr_uid where ad.del_thread_status = 'closed' group by ad.usr_username 	0.424077722561065
19650208	30579	how to check which tables in db (mysql) updated in last 1 hour/1day	select id, updated from foo where updated >= now() - interval 1 hour order by updated desc 	0
19653743	596	limit by different field than order in mysql statement?	select * from (select table1.*, count(table2.link_id) as count from table1     left join table2 on (table1.key = table2.link_id) group by table1.key order by count desc limit 20 ) t order by name asc 	0.0351016334416804
19656213	5251	different casting of int to guid in c# and sql server	select cast(convert(binary(16), reverse(convert(binary(16), 1000))) as uniqueidentifier) 	0.129354503140301
19657274	38937	adding a select and joins to already existant complex query	select r.refnam,         t.tstring,        rc.cnt namecounter,        d.alarmzu from refdev r inner join (select refnam,                     count(*) cnt               from refdev rc           group by refnam            ) rc          on rc.refnam = r.refnam left outer join texte t              on r.sigtnr = t.textnr join devtzu d on d.zustnr = r.zustnr left outer join refdev_def rd on d.dvtypnr = rd.dvtypnr where r.refnam = rd.refnam and rc.cnt = 3 order by r.refnam 	0.705836077155839
19660194	1742	combining the results of two joins in sql	select [test_db].[dbo].[tickets].*, [test_db].[dbo].[notes].* from [test_db].[dbo].[tickets] inner join [test_db].[dbo].[movies] on  [test_db].[dbo].[tickets].[connectedto] = [test_db].[dbo].[movies].[movieid] inner join [test_db].[dbo].[notes] on [test_db].[dbo].[tickets].[ticketid] = [test_db].[dbo].[notes].[connectedto] where [test_db].[dbo].[tickets].[dateentered] >= dateadd(month, datediff(month, 0, getdate())-1, 0)    and [test_db].[dbo].[tickets].[dateentered] <= dateadd(month, datediff(month, 0, getdate()), -1) 	0.0259218099070341
19660810	35196	select top 4 with order by, but only if actually required?	select top 4     m.somefield,     m.somefield * 1/f.functionresults [someotherfield] from #mytemptable m cross apply (select dbo.myfunction(m.param1, m.param2, 34892)) f(functionresults) order by f.functionresults 	0.0287193942786323
19675273	34383	show max date of customer	select p_master.pid, visit_date, (select max(visit_date) from p_visit v where v.pid = p_master.pid) as maxvisit from p_master left join p_visit on p_master.pid=p_visit.pid where cast(convert(varchar(10), visit_date, 101) as datetime)='2013-10-29' 	0.000105475747961817
19677205	33905	how to make inner join with two conditions in mysql	select posts.*,        u1.username as poster_username,        u2.username as posted_username from posts inner join users u1 on posts.poster_id = u1.id  inner join users u2 on posts.posted_id = u2.id  order by timestamp desc  limit 0,10 	0.663287862364619
19680176	31088	mysql group rows by date into 4 seasons + year	select case when month(news_date) between 3 and 5 then 'spring',             when month(news_date) between 6 and 8 then 'summer',             when month(news_date) between 9 and 11 then 'autum',             when month(news_date) >= 12 and month(news_date) <= 2 then 'winter'        end as period,        year(news_date) as year,        count(news_id) as count from news where news_type = 'news' and news_status = 'enabled' group by year(news_date), period order by news_date desc 	0.000103439183950065
19682050	34392	how to select max value from 2 tables in mysql	select ifnull(max(id), 0) id from (     select id from table1     union all     select id from table2 ) a 	9.87948792563638e-05
19695948	19151	how to fetch unique(pkid, column1,column2) from mysql?	select pkid,column1,column2  from my_table group by pkid,column1,column2 	0.0140532079470996
19706028	11278	sql - comparing against multiple values in the same column?	select * from t t1 where status='h' and not exists(     select *      from t t2      where t1.id=t2.id and t2.status='a' and t2.stat_date > t1.stat_date) 	0.000217222170614215
19718645	25282	i want to fetch the data from three tables which have many to many relationship using mysqli statement query	select u.username, u.fname, u.lname, a.title, ua.ip_address, ua.date_time from users u left join user_activity ua on ua.user_id = u.uid left join activity a on a.id = ua.act_id 	0.000120450023508435
19766046	18281	display data from 3 tables when i select a name from combo box	select table1.sfirst, table1.slast, table2.sdob, table3.scode from table1  inner join table2 on table1.keycol=table2.keycol inner join table3 on table2.keycol=table3.keycol where table1.last='some value' 	8.4608830938044e-05
19773817	38040	mysql refuses to use index	select taskid from tasktransitions force index (transitiondate_ix) where transitiondate>'2013-09-31 00:00:00'; 	0.773608077708865
19781083	26983	mysql pivot tables - covert rows to columns	select date,        max(case when index_name = 'alerian mlp pr usd' then results end) `alerian mlp pr usd`,        max(case when index_name = 'msci eafe mid nr usd' then results end) `msci eafe mid nr usd`   from mst_ind  where index_name in ('msci eafe mid nr usd', 'alerian mlp pr usd')     and time_period = 'm1'  group by date 	0.00380732284086995
19782098	7286	where clause based upon the null and non null column in sql server	select top 1 * from table1  where col1 = @param1 and (col2 is null or col2 = @param2) order by case when col2 is null then 1 else 0 end 	0.0147555399798326
19782254	23922	select query with count and having by	select pl.*, u.* from users as u join (     select          userid,         substring_index(group_concat(post_id order by post_id desc), ',', 5) as last_5_posts     from post_list     group by userid ) as pl5 on(u.id = pl5.userid) join post_list as pl on (find_in_set(pl.post_id, pl5.last_5_posts)) order by pl.post_id desc limit 50 	0.388302172781513
19791301	6346	pending friend request query for friends table and grabbing data from other tables	select u.name_surname,         u.avatar,        group_concat(distinct w.word order by w.word asc) as words from users u inner join  ( select f1.asker_user_id as friend_id     from friends as f1      left join friends as f2         on f1.asked_user_id = f2.asker_user_id         and f1.asker_user_id = f2.asked_user_id        where f1.status = 1 and f2.status is null     and f1.asked_user_id = 2 ) a on a.friend_id = u.id left join connections c on u.id = c.user_id left join words_en w on w.id = c.word_id group by u.id; 	0
19795707	2206	find xml elements name in sql	select     t.c.value('local-name(.)', 'nvarchar(max)') as name from @xml.nodes('d/*') as t(c) 	0.00223880037163602
19810799	27943	mysql: display duplicates matching two columns	select id, shipping_date from t group by id, shipping_date having count(*) > 1; 	0
19814654	3132	how to compare the value of two rows with sql?	select a.* from   (select name, dt, sum(score) as sum_score          from   performance          group by name, dt) a join   (select name, dt, sum(score) as sum_score         from   performance          group by name, dt) b on     a.name = b.name and a.sum_score = b.sum_score and a.dt < b.dt 	0
19826874	19539	sql: find highest number if its in nvarchar format containing special characters	select max(cast(replace(column2, '.', '') as int)) from table 	0
19832049	37162	how to substract cummulative in sql from column to column	select     contact ,   customers ,   (select sum(customers) from mytable t2 where t2.contact >= t1.contact) as cummcustomers from mytable t1 	0.00598126889125674
19835165	22452	remove carriage returns in text column during mysql query in php script	select replace(marketing_remarks, '\r', '') as marketingremarks where column = "blah" 	0.0963397978880751
19841508	40239	remove simetrics tuples in sql select	select i1.prodid,        i2,prodid  from inventory as i1,      inventory as i2 where i1.color=i2.color   and (        i1.prodid || '-' || i2,prodid <>  i2.prodid || '-' || i1,prodid         or        (           i1.prodid || '-' || i2,prodid <>  i2.prodid || '-' || i1,prodid            and           i1.prodid  < i2.prodid         )       ) order by i1.prodid 	0.0569998096988272
19843676	5556	concat search in columns	select   people.name, people.secondname   concat(people.name," ", people.secondname) from people left outer join shop on concat(people.name," ", people.secondname) = shop.buyer  left outer join circus on  concat(people.name," ", people.secondname) = circus.watcher where shop.buyer is null and  circus.watcher is null 	0.105532244739168
19849863	12217	multi layered mysql call within php	select *  from registrar_claims  where reg_region in (select region from regions where staff_100_id='$id')     and ready_to_process='yes' order by claim_id asc 	0.686183010724848
19852237	36027	multi coloumn search in sqlite	select * from mytable where (col1 || ' ' || col2) like '%abc xyz 123%' 	0.419241524062841
19852241	18896	how to combine results of two different queries from one table mysql	select usd.regdate, usd.averages as usd, gbp.averages as gbp from (select regdate, averages from table1 where code = 'usd') usd inner join (select regdate, averages from table1 where code = 'gbp') gbp on usd.regdate = gbp.regdate 	0
19860008	28602	mysql table structure with one row. best handling for management and insertion	select * from [uid]_data ... select * from [uid]_data join ... update [uid]_data ... insert into [uid]_data ... delete from [uid]_data  	0.580264714703453
19862099	8066	sql server - select distinct random number of rows	select top (100) min(c.id), u.id, u.name, min(b.sector), min(u.default) from cads as c  inner join users as u on c.cad = u.id  inner join business as b on u.id = b.cad where (c.[public] = 'true') and (c.valid = 'true')          and (u.default = '$curr')          and (c.expires is null or c.expires >= getdate()) group by u.id, u.name  order by newid() 	0.000240133627518254
19866872	11275	sql or msexcel transpose data from rows to columns not pivot nor transform	select * from tablename pivot( max(answer) for question in ([question1], [question2],[question3],[question4],[question5])) as pivottable 	0.0027505034587642
19875363	7555	using distinct dates and aggregate functions with postgres	select date_trunc('month', event_logs.start_at) as start_at,  avg(event_logs.head_count) as head_count  from "event_logs"  where ("event_logs"."state" in ('completed'))  and ("event_logs"."start_at"  between '2013-05-09 10:12:58.824846' and '2013-11-09')  group by date_trunc('month', event_logs.start_at) 	0.511138572869279
19882942	32660	sqlite select minimum and maximum from two tables	select max(case c1 when min1 then c2 end) c2_first,         max(case c1 when max1 then c2 end) c2_last  from (select c1t1 c1, c2t1 c2 from table1        union all        select c1t2 c1, c2t2 c2 from table2) u cross join (select min(min11, min12) min1, max(max11, max12) max1 from  (select min(c1t1) min11, max(c1t1) max11 from table1) t1  cross join  (select min(c1t2) min12, max(c1t2) max12 from table2) t2) m 	0
19883743	25350	retrieve name of those who are 60 years or older, mysql	select * from employee where timestampdiff(year,bdate,curdate())>= 60 	0
19884319	8056	sqlite select statment on one table	select s.game, s.type, s.score, min(t.time) as time from (     select tt.game, tt.type, max(tt.score) as score      from table tt      group by tt.game, tt.type ) s  inner join table t on s.game = t.game and s.type = t.type and s.score = t.score group by s.game, s.type, s.score 	0.0191192912844015
19896412	26319	how to select date from h2 database	select id from contest where contest_date = '2004-03-01'; 	0.00563811553835764
19907631	23729	mysql: filter on multiple values in different rows but return only rows that match both values	select product_id  from your_table  where option_id in (20,28)  group by product_id having count(distinct option_id) = 2 	0
19909230	19803	sql - select * from table order by	select name from tbl group by name order by  case when name = 'bgin' then 0      when name = 'mid' then 5      when name <> 'mid' and name <> 'bgin' then 1 end, name 	0.0169957752802059
19921553	4618	take string value in where clause - mysql	select * from `vehicle_duty_chart` where trim(models) = "se3p" limit 0 , 30 	0.0618506409722524
19927930	35917	sql select where not matching specific selection	select distinct name from events t1 left join userhistory t2 on t1.name = t2.event and t2.certain_column = 1234 where t2.event is null 	0.0699191644937621
19929317	32223	divide a column into two based on another column value - oracle	select   min(id) id   name,    max(case when recipient_sender=1 then user else null end) sender,    max(case when recipient_sender=2 then user else null end) recipient from yourtable  group by name 	0
19939818	39907	query effeciency, 3 child tables to 1 parent	select t_id_fk  from  transaction_ch_a where t_id_fk  is not null union all  select  t_id_fk   from transaction_ch_b where t_id_fk  is not null union all  select   t_id_fk  from transaction_ch_c where t_id_fk  is not null 	0.00144662930570722
19942201	17536	calculating total sales from multiple mysql tables	select employees.eno, employees.ename, sum(parts.price * odetails.qty) as totalsales from test.employees inner join test.orders on empoyee.eno = orders.eno inner join test.odetails on orders.ono = odetails.ono inner join test.parts on odetails.pno = parts.pno group by employees.eno, employees.ename 	0
19948793	4319	mysql select column outside group by	select rates.* from xrates rates where id in  (     select min(xrates.id) as minid         from xrates     inner join     (         select c1, c2, min(xr) as minxr         from xrates         group by c1, c2         having c1 = 'gbp'     ) x on x.c1 = xrates.c1 and x.c2 = xrates.c2 and x.minxr = xrates.xr     group by xrates.c1, xrates.c2 ) 	0.0797097414801603
19951233	31966	mysql get status of all records from associative table	select a.id, if(i.current is null, 0, current) as status from album a left join (     select albumid, min(current) as current     from icon_album     group by albumid ) i on a.id = i.albumid 	0
19954416	38502	how to get vistors_sum and reviews_count in 3 table?	select a.products_id,        products_name,        coalesce(b.sum_visitors,0) as sum_visitors,        coalesce(c.count_comments,0) as count_comments from a left join  ( select products_id,sum(vistors) as sum_visitors    from b    where date='2013-11-13'   group by products_id ) as b on (a.products_id=b.products_id)  left join  (   select products_id,count(*) as count_comments    from c    where date='2013-11-13'   group by products_id ) as c   on (a.products_id=c.products_id) 	0.00257890708778174
19955162	36632	sql inventory with history	select * from tablename t1 where t1.date =        (select max(t2.date)           from tablename t2         where t2.id = t1.id and t2.warehouse = t1.warehouse) 	0.407142544685906
19966123	19870	get time interval in mysql	select * from tbl  where tbl.mydate > date(date_sub(now(), interval 45 minute))  and tbl.mydate < date(date_sub(now(), interval 30 minute)); 	0.00732639871498578
19971209	20992	mysql pivot table group by two columns	select `bills_organization`.`name`,         sum(`bills_bill`.`os_status`=1) as unnknown,         sum(`bills_bill`.`os_status`=2) as introduced,         sum(`bills_bill`.`os_status`=3) as passedonechamber,         sum(`bills_bill`.`os_status`=4) as passedbothchambers,         sum(`bills_bill`.`os_status`=5) as enacted from `bills_mybill`  inner join `auth_user` on (`bills_mybill`.`user_id` = `auth_user`.`id`)  left outer join `bills_bill` on (`bills_mybill`.`bill_id` = `bills_bill`.`id`)  left outer join `bills_userprofile` on (`auth_user`.`id` = `bills_userprofile`.`user_id`)  left outer join `bills_organization` on (`bills_userprofile`.`organization_id` = `bills_organization`.`id`)  where `bills_mybill`.`favorite` = true   group by `bills_organization`.`name` 	0.00774967439587015
19975322	22068	get the difference of two column in two different tables?	select a.counter,            a.total_qty,            a.total_qty - b.qty balance        from (select counter,                    sum(total_qty) total_qty               form purchase_request           group by counter) a  inner join (select counter,                    sum(qty) qty               from purchase_order            group by counter) b          on a.counter= b.counter    group by a.counter 	0
19975769	32438	how to find change in column from table?	select pnum,count(distinct cur) changecount from table group by pnum having count(distinct cur)>1 	0.000199782413237513
19979532	22982	convert int to varchar sql	select convert(varchar(10), field_name) from table_name 	0.168785988677242
19981150	7692	select some items and if there's not enough of them, add some other items, then sort	select * from (     select * from `items` where important = 1 or type = 'news'      order by `important` desc, `date` desc limit 3 ) x order by `date` desc 	0
19983334	35455	need to find value in one column and then return value from another column	select t.avalue,        case t.avalue          when t.actualcolumn1 then t.relativecolumn1          when t.actualcolumn2 then t.relativecolumn2          when t.actualcolumn3 then t.relativecolumn3          when t.actualcolumn4 then t.relativecolumn4        end as rvalue from t 	0
19992155	6096	sql one to many join - do not return rows from the 'one' table if any row in the 'many' table equals x	select * from order_items o where item_number not in (     select item_number     from processes     where process_number in (1, 2, 3)     ) 	0
19994634	36738	mysql query for the following	select t.ch, t.value from test t   join (     select ch, count(distinct value) as 'dst'     from test     group by ch     having count(distinct value)=1   ) as q on t.ch!=q.ch; 	0.446875228073066
19998363	10614	query to find the cases of cholera by age	select id, schoolid, sex, age, diagnose from tbl_1 where diagnose = 'cholera' union all select id, patientid, sex, age, diagnose  from tbl_2 where diagnose = 'cholera' order by age, sex; 	0.0026452817026372
20000826	30025	get field value in the same row where max(field) limit 1	select developer from app where downloads = (select max(downloads) as maxdownloads from app); 	0
20008720	35117	how to use skip column name in select query in mysql	select t1.location,   max(case when t2.locationid = '2847' then t2.value end) mr,   max(case when t2.locationid = '2839' then t2.value end) flow,   max(case when t2.locationid = '2834' then t2.value end) pressure,   max(case when t2.locationid = '2836' then t2.value end) level from table2 t2 inner join table1 t1 on t1.id = '2847' where now() - interval 4 hour >= from_unixtime(t2.t_stamp/1000)  group by t1.location 	0.0417199405570851
20027561	30055	mysql: returning total record count from a cross joined row?	select names.pid, name, count(extra) as total  from names  left join info  on info.pid=names.pid  group by names.pid 	0
20042421	17264	my sql query with two tables	select p.name from person p inner join person_sibling s on p.id = s.id inner join person sp on s.sibling_id = sp.id where p.age > sp.age 	0.323951171599432
20045045	39944	oracle get numbers with range	select    distinct start_serial+level-1 serial from    yourtable connect by level-1<=end_serial-start_serial order by 1; 	0.0018370137661306
20054900	16364	sql table -- how to write a query to determine whether a team has scored more points in the first half or second half of the year	select sum(if(dateofgames <= '2013-06-30', pointsscoredbyteam, 0)) as `first_half_points`,     sum(if(dateofgames > '2013-06-30', pointsscoredbyteam, 0)) as `second_half_points` from yourtable where `team name` = 'liverpoolfc'     and dateofgames >= '2013-01-01'     and dateofgames < '2014-01-01' 	0
20061274	740	how to count number of unique (by 3rd field in a whole set) ids by type	select   type, count(*) from     (select acc_fk, type from t1 group by acc_fk) t group by type 	0
20063521	35149	oracle counting null value, which is more appropriate?	select sum(n_count), sum(x_count) from      (select case when resp_cd is null then 1 end n_count,           case when resp_cd = 'x' then 1 end x_count      from your_table      ); 	0.164963362001742
20081493	18131	how to select by two unique field values in mysql	select examid, level, max(`points`) from score group by examid, level order by id 	0.000113689527947059
20091125	16055	nth max salary in oracle	select *   from   (     select         sal           ,dense_rank() over (order by sal desc) ranking     from   table   )   where ranking = 4  	0.00556545066502508
20099090	31697	how can i list all postgres rules using sql?	select n.nspname as rule_schema,         c.relname as rule_table,         case r.ev_type            when '1' then 'select'           when '2' then 'update'           when '3' then 'insert'           when '4' then 'delete'           else 'unknown'         end as rule_event from pg_rewrite r     join pg_class c on r.ev_class = c.oid    left join pg_namespace n on n.oid = c.relnamespace    left join pg_description d on r.oid = d.objoid 	0.0165714379135534
20102765	34680	i need to sum column values for the curren month only	select sum(_value) from tableactone where strftime('%m', date_col) = strftime('%m', (       select date ('now')       ))   and strftime('%y', date_col) = strftime('%y', (       select date ('now')       )) 	4.86778960483158e-05
20108586	18228	filemaker sql - fetch column2 from records with distinct column1	select account, max(id) from albums2 group by account 	4.98134660075532e-05
20117510	21641	sql which query to join tables	select id_news,n.title, group_concat(c.content) from news n left join comments c on n.id=c.id_news group by n.id 	0.231564041367067
20118040	9894	insert data into temp table from 2 source tables	select a.impos, b.code from (   (     select impos, rank() over (order by impos asc) as link     from table1     ) as a inner join (     select code, rank() over (order by code asc) as link     from table2     ) as b on a.link = b.link   ) 	5.74943583439565e-05
20120822	27113	mysql self join produces duplicate entries	select p1.last_name, p1.first_name, p1.city, p1.state from president as p1 inner join president as p2 on p1.city = p2.city and p1.state = p2.state where (p1.last_name <> p2.last_name or p1.first_name <> p2.first_name) group by p1.last_name, p1.first_name, p1.city, p1.state order by state, city, last_name 	0.112845182498669
20129419	6977	need two calculated field but based on different where clause	select  employeename,  avg(case when table.optyid is null then leadamount end) as [avglead],  sum(case when table.optyid is not null then quota end) as [quota] from table group by employeename 	0.00069295905805655
20137053	38797	summarize mysql data using group by or any other method	select user_id, date, min(start_time) start_time, max(end_time) end_time   from (   select user_id, date, start_time, end_time,          @n := if(@u = user_id and @d = date and cast(@e as time) = start_time, @n, @n + 1) rnum,          @u := user_id, @d := date, @e := end_time     from table1 cross join (select @n := 0, @u := null, @d := null, @e := null) i    order by user_id, date, start_time, end_time ) q  group by user_id, date, rnum 	0.376194509092238
20137691	11156	add number of days in given date	select date(now()+duration * interval '1day') from tbl; 	0
20153442	30649	sql server : concatenate data result in to a table format	select column1, data from mytable cross apply dbo.split(column2, ',') 	0.00210670649179819
20164782	6699	sql calculate average	select t.districtname, t.townname, t.varietyofcrop, avg(cast(t.pests as float)) from finaltable2 t group by t.districtname, t.townname, t.varietyofcrop 	0.00452435425140974
20166402	35957	how do i select records with max from id column if two of three other fields are identical	select cc.* from      consumable_cost as cc     inner join     (         select              max(consumable_cost_id) as max_id,              consumable_type_id,             from_date         from consumable_cost         group by consumable_type_id, from_date     ) as m         on cc.consumable_cost_id = m.max_id 	0
20175894	22279	extracting n number of rows from a table	select material, count(*) from (   select top 5 material from sale  ) a group by material 	0
20176091	21149	find most common value of a table	select name from players p  inner join player_frags pf on pf.lasthit = p.name  or pf.mostdamage = p.name group by name order by count(*) desc 	0
20179369	1891	how to retrieve the last row (by time) from each user	select x.*   from views x   join (select user_id,max(view_id) max_view_id from views group by user_id) y     on y.user_id = x.user_id    and y.max_view_id = x.view_id; 	0
20179535	35723	giving the total orderprice of a user without duplicate	select customer.custno, custname, custstreet, custcity, sum(orderprice)       from customer, orderprod, orders      where custcity = 'brampton'        and customer.custno = orders.custno   group by customer.custno, custname, custstreet, custcity     having sum(orderprice) > 500.00; 	0.000284223645359532
20186120	26583	select employee_name, count(dependent) as dependents from employee error	select e.employee_id,e.employee_name,count(d.employee_id) as dependents      from department d      inner join employee e on (e.employee_id=d.employee_id)       group by d.employee_id; 	0.202149831393468
20193359	577	sqlite count members in a group	select gu1.group_id_foreign      , count(*) ttl    from group_participants gu1   join group_participants gu2     on gu2.group_id_foreign = gu1.group_id_foreign  where gu1.user_id_foreign = 1  group      by gu1.group_id_foreign; 	0.067489095439085
20208885	28348	pick a random attribute from group in redshift	select id, first_value as attribute  from(select id, first_value(attribute)      over(partition by id order by random()      rows between unbounded preceding and unbounded following)      from dataset)  group by id, attribute order by id; 	0.00089654098356527
20213704	26451	sql server 2008 sort with aa above a	select * from yourtable order by case when yourcolumn = 'aa' then 1 else 2 end, yourcolumn 	0.477748199824284
20214968	36772	inner join and union all using order by	select image_id_fav,image_path_fav from ( select b.image_id as image_id_fav, i.image_path as image_path_fav,         f.favorite_id as favid from buddies b inner join @favdt f on f.favorite_id = b.reg_id and b.favorite_id = @regid inner join images i on i.image_id = b.image_id where b.image_id > 0 union all select i.image_id as image_id_fav, i.image_path as image_path_fav,         f.favorite_id from buddies b inner join @favdt f on f.favorite_id = b.reg_id and b.favorite_id = @regid inner join registration r on r.reg_id = f.favorite_id inner join images i on r.default_image = i.image_id where b.image_id = 0 union all select i.image_id as image_id_fav, i.image_path as image_path_fav,         f.favorite_id from @favdt f left outer join buddies b on b.reg_id = f.favorite_id and b.favorite_id = @regid inner join registration r on r.reg_id = f.favorite_id inner join images i on r.default_image = i.image_id where b.reg_id is null ) order by favid 	0.586157036586524
20229744	11191	sql find missing records with a join on null	select   parents.id from   container children     left join   container parents on (parents.id = children.parent_id) where   parents.id is null; 	0.0139282725666973
20235022	29232	mysql - get the last activities of a user	select v.user_id, v.date_added, v.vote from vote as v  join discussion as d on d.user_id=v.user_id join comments as c on c.user_id=v.user_id order by v.date_added desc 	0
20242171	27080	multiple nested queries to count total of each category	select empname,        sum(case when flag = 1 then 1 else 0 end) as completecalls,        sum(case when flag = 0 then 1 else 0 end) as incompletecalls from call_log group by empname 	0
20247921	32681	reshaping/transforming results in a column to remove some values	select replace(replace(rc.name,'qpt ',''), ' dd','') from ... 	0.00168400687410914
20252926	17278	how to summarize the multiplication of two columns per each row	select sum(x * y) as totalcapacity from   bedrooms 	0
20258286	725	how to join tables based on the dates	select o.*, (   select top 1 commission     from commission    where product_id = o.product_id      and date <= o.date    order by date desc ) commission   from [order] o 	0.000198329306212483
20267374	27063	sql server join two tables with where condition on both tables	select      clinical_study.nct_id, clinical_study.brief_summary, clinical_study.study_type, clinical_study.gender, location_countries.country from clinical_study inner join location_countries on clinical_study.nct_id=location_countries.nct_id where (clinical_study.gender like'male' or clinical_study.gender like 'both') and  location_countries.country ='united kingdom' 	0.0643402623693592
20277124	18540	mysql query for a simple table	select a.size,sum(a.qty),a.status from table a inner join table b on a.id=b.id group by a.size 	0.690032635201196
20280301	24198	select other record using subquery	select c.customer_id, c.customer_name, min(o.date) date from customers c left join orders o using (customer_id) group by c.customer_id 	0.0166498540178273
20285625	36968	sql server : select from duplicate columns where date newest	select t1.* from your_table t1 inner join (   select sid, max(convert(date, invite_date)) mdate   from your_table   group by sid ) t2 on t1.sid = t2.sid and convert(date, t1.invite_date) = t2.mdate 	7.32642162131544e-05
20315430	4738	sql server: grouping items not working	select     lr.categoryx,     count(*) as groupcount,     max(lr.datex) as groupnewest,     (         select t.itemid         from logrequests as t         where t.logstatus = 'active' and t.categoryx = lr.categoryx         for xml path(''), type     ) from logrequests as lr where lr.logstatus = 'active' group by lr.categoryx for xml path('categoryx'), root('ranks') 	0.744583740693688
20317257	232	get unique users by date	select from_unixtime(utc_timestamp, 'yyyy-mm-dd'), s from evt where month = 201311 group by from_unixtime(utc_timestamp, 'yyyy-mm-dd'), s 	0.000216904552399421
20330146	33765	cross table query for showing comments and thread name while both values in different table	select c.*, t.* from comments c  left join threads t on t.id = c.thread_id where c.username = 'username' 	0.000140255893367291
20332632	11026	sql query help - maximum date required	select * from (  , row_number() over (partition by cust_retail_channel_name order by addressvalidfrom desc) as rnk ) d where d.rnk=1 	0.363193828132513
20333830	24907	sql update same table	select legacyfullpathnme into newtable from oldtable group by legacyfullpathnme; 	0.0176363573018365
20335782	37483	how to control the output format of xml in sql	select   country [@country],   (select     product [@product],     (select       disposition [@reasoncode],       results [@count]     from #xmlresults t3     where t3.country = t1.country and t3.product = t2.product     for xml path('disposition'),type)   from #xmlresults  t2   where t2.country = t1.country   group by product   for xml path('product'),type) from #xmlresults  t1 group by country for xml path('country'), root ('stats') 	0.0536373155765535
20340689	3126	sql query with multiple values in table a whose description is in table b	select territory, g1.group_description as desc1 , g2.group_description as desc2 , g3.group_description as desc3 , g4.group_description as desc4  from territory t     left outer join [territory_group] g1 on t.group_id1 = g1.group_id    left outer join [territory_group] g2 on t.group_id2 = g2.group_id    left outer join [territory_group] g3 on t.group_id3 = g3.group_id    left outer join [territory_group] g4 on t.group_id4 = g4.group_id 	0.000155094598127962
20341255	5434	month to date query	select installed_date,cust_no,sum(price) as daily_price from table1 where installed_date >= dateadd(month, datediff(month,0, current_timestamp), 0) group by installed_date,cust_no 	0.00558825992326558
20343729	27781	group by months and display chronologically and not alphabetically in mysql	select   concat(monthname(a.fdate),'-',year(a.fdate)) month,   s.new_state state,   d.new_dist district,   b.ifbook book,   sum(a.amt) amount from str a join sc b on b.scd = a.isc join user c on a.ed = c.str join state_mapping s on b.state = s.org_state join dist_mapping d on b.dist = d.org_dist where trim(b.ifbook) <> '' and b.ifbook is not null and b.ifbook not like '%tr%'   and trim(d.new_dist) <> '' and d.new_dist is not null group by b.ifbank, d.new_dist, s.new_state, month order by year(a.fdate), month(a.fdate) 	0.00396462048467558
20343971	13420	my sql remove doublicates values	select min(id), name from notes group by name 	0.130615924164322
20352474	21533	how to get two table row together	select f.flatsno, f.buildingname, ifnull(c.status,f.status) as status, f.flattype  from `flats` f left join `contract` c on f.flatsno = c.flatno and f.buildingname = c.buildingname where f.buildingname = "building1" order by f.flatsno asc 	0.000106353753317098
20353976	22774	mysql query count fields	select s.name as student_name,         c.name as course_name,         p.name as place_name,         count(*) from students s inner join student_to_courses s2c on s.id = s2c.participation_id inner join courses c on c.id = s2c.course_id inner join places p on p.id = c.place_id inner join students_participation sp on s.id = sp.profile_id where s2c.course_id = 1 group by s.name,c.name,p.name 	0.148487102895674
20354036	1788	firebird: sum of the multiplication of two fields within a select statement	select       d.id,     d.name,     sum(case when d.sale_unity = 'k'          then (d.cost_price * ci.quantity_k)         else (d.cost_price * ci.quantity_u) end ) as total_cost,     sum(case when d.sale_unity = 'k'          then (d.sale_price * ci.quantity_k)         else (d.sale_price * ci.quantity_u) end ) as net from detail d inner join voucher as v on v.id = d.voucher_id where v.client_id = 97 and v.date between '06/01/2012' and '07/01/2012' group by d.id, d.name 	0.000758905758876747
20357505	34615	mysql output two columns for data in one column	select date_format(timestamp, '%h:%i:%s') as timestamp,  sum(case when action = 'dropped' then 1 else 0 end)as denied, sum(case when action = 'allowed' then 1 else 0 end)as allowed  from events where timestamp >= '2013-11-01 00:00:00'   and timestamp <= '2013-11-01 01:00:00' group by unix_timestamp(timestamp) div 300 limit 3; 	0.000173472603994407
20371165	22178	oracle: query records where creation date is within 6 months prior to today's date	select itemname,            username,         to_char(createdate, 'mm') month,         to_char(createdate, 'yyyy') year,         count(*) item_count from   tablename where  createdate between add_months(trunc(sysdate,'month'), -6) and last_day(trunc(sysdate, 'month') - 1) group by itemname,username,to_char(createdate, 'mm'), to_char(createdate, 'yyyy') order by month, year; 	0
20383944	31852	how to achieve this complex sum of 2 rows from a mysql result set?	select * from(select v.*, if(date_format(date, '%m') != @month, @month_sum := credit + debit, @month_sum := @month_sum + (credit + debit)) as month_sum, @total_sum := @total_sum + (credit + debit) as total_sum, @month := date_format(date,'%m') as month from tbl_values v join (select @month := 0, @month_sum := 0, @total_sum := 0) d order by date asc)z limit 2 	0.0860944348321794
20385115	18083	query a join where a specific key value row does not exist	select sum(o.order_total) as total from orders o inner join order_meta pm on pm.order_id = o.id left join order_meta om on om.order_id = o.id and om.type = 'promo' where pm.type = 'price_group' and pm.value = 1 and om.id is null 	0.0155510119206729
20390335	7624	in tsql, how to calculate time duration across 2 tables (login & logout logs)?	select ul.*, datediff(minute, datetime, logouttime) as duration from (select ulil.*,              (select top 1 ulol.datetime               from userlogoutlog_201307 ulol               where ulil.accountid = ulol.accountid and                     ulol.datetime > ulil.datetime              ) as logouttime       from userloginlog_201307 ulil      ) ul; 	0.000172130085511014
20394278	25846	mysql query return multiple columns	select bestloc  from nutrients  where foodid = "$foodid"  and compid in ('0000','0001','0003','0008','0130') 	0.0212713184412362
20395573	10415	prevent sql double booking	select r.rumsnummer from rum r where not exists (             select rb.rumsnummer             from rumsbokning rb             where                  r.rumid = rb.rumid                 and rb.datumfrån >= @datumfrom                  and rb.datumtill <= @datumtill ) 	0.749868712190722
20420708	40074	convert query result to array	select array_agg(x."id")  as "id" from public."jp_onlyids" as x 	0.138202914888917
20422473	41195	select record based on status if it exists	select a.id, a.shipmentno, a.status, a.date  from (select a.id, a.shipmentno, a.status, a.date        from shipment a order by a.shipmentno, field(a.status, 's', 'i')       where a.date = '2013-12-12'       ) a group by a.shipmentno 	0.000165514635749962
20431305	7449	mysqli query auto-escaping	select * from movie_quotes where text = 'i can''t stand him.'; 	0.669050333471343
20441343	19286	calculate value of attribute using number of occurences in another table?	select number_of_seats -     (select count(*) from reservations where reservations.trip_id = trips.trip_id) from trips 	0
20453123	9426	how to query the second column of a join table?	select distinct pfriend.idperson, pfriend.name from people_friends pf  inner join person pfriend on pf.otherperson_id = pfriend.idperson where pf.person_id = 4 	0.000338904180024525
20459660	20058	how can i join a table from two keys referencing same table with sql server?	select cc.rate, cc.sourcecurrencyid , cc.targetcurrencyid,                  src.code as 'sourcecurrencycode', tgt.code as 'targetcurrencycode' from currencyconversion cc  inner join currency src on cc.sourcecurrencyid = src.id   inner join currency tgt on cc.targetcurrencyid = tgt.id 	0.00044511397202945
20461991	19528	how to multiply and divide in from multiple querys?	select (   (     select count(*)     from   drink d join history  h on h.drinkname = d.name     where  type = 'vodka' and userid = 'sai'   ) + (     select count(*)     from   drink d join favorite f on f.drinkname = d.name     where  type = 'vodka' and userid = 'sai'    ) ) / (   (     select count(*) from history  where userid = 'sai'   ) + (     select count(*) from favorite where userid = 'sai'   ) ) 	0.00477707170784649
20462153	36967	check user status as part of sql query	select vouchers.code, count(voucher_credits.voucher_id) as activated from vouchers, voucher_credits, users where vouchers.code like '%sentme%'      and vouchers.id = voucher_credits.voucher_id     and voucher_credits.remaining_credit = 0     and users.id = voucher_credits.user_id and user.state = 'active' group by vouchers.code order by count(voucher_credits.voucher_id) desc limit 50 	0.00532923493225464
20485672	33690	using sql to get the minimal unused number from a set of continuously increasing numbers	select number + 1 first_unused   from  (   select 499 number    union all   select number      from table1    where number >= 500 ) t  where not exists (   select *     from table1    where number = t.number + 1 ) limit 1 	0
20494022	20529	selecting data between dates in sql	select status,        startdate,        lead(startdate, 1,null)           over (order by startdate)          as enddate from t order by startdate 	0.00120928691552025
20505168	33597	sql/criteria query contains all?	select tablea.id, count(*) from tablea join tablea_b on tablea.id=tablea_b.a_id where b_id =1 or b_id=2 group by tablea.id having count(*)=2 	0.0307363487439847
20521348	9374	insert record for each unique column value	select distinct    filename,   vals from     (select          filename,         a1,         a2,         a3    from        foo) p unpivot    (vals for counts in        (a1,a2,a3) ) as bar 	0
20522359	38326	adding aliasing to field names in pivot sql query	select emp, rvwr,     [cmp-goal-rf-148] as ghost   from  (    select emprvwpddtl.emp, emprvwpddtl.rvwr,       emprvwpddtl.rvwitm,       cast(emprvwpddtl.rvwitmcom as varchar(max)) as comment     from emprvwpddtl    inner join emprvwpd       on (emprvwpd.emp=emprvwpddtl.emp)    where emprvwpddtl.rvwitmcom  is not null      and emprvwpd.sup='rm04' ) as s pivot  (    max(comment) for rvwitm in ([cmp-goal-rf-148]) ) as pvit 	0.333133875262729
20546761	4059	sql query select each type of form per employee	select  employeeid,     sum(case when f.id = 1 then 1 else 0 end) formtype1,     sum(case when f.id = 2 then 1 else 0 end) formtype2,     sum(case when f.id = 3 then 1 else 0 end) formtype3,     sum(case when f.id = 4 then 1 else 0 end) formtype4,     sum(case when f.id = 5 then 1 else 0 end) formtype5,     sum(case when f.id = 6 then 1 else 0 end) formtype6 from forms as f group by employeeid 	0
20570351	31212	hql how to join three table	select i from inventory i,category c inner join i.product ip inner join c.products cp where ip = cp and c.id=? 	0.324613101526218
20587928	1586	how to join or subquery a table representing tiers	select i.id, i.price, max(f.fee), i.price + max(f.fee)  from item i inner join fee f on i.price > f.cutoff group by i.id, i.price 	0.601180964544816
20588202	13679	selecting entries that appear in two places	select * from author where aid in (   select aid from writes where pid in   (     select pid from paper where isbn in     (       select isbn from book where title = 'artificial intelligence'     )   ) ) and aid in (   select aid from writes where pid in   (     select pid from paper where isbn in     (       select isbn from book where title = 'generic algorithms'     )   ) ); 	0
20609343	9365	merge two columns from two tables into one	select shopy as y from shops  union all  select y from infra  order by y asc 	0
20610523	33540	find mean of difference between dates -sql select	select  b1.repid ,       avg(abs(datediff(hour, b1.builddate, b2.builddate))) from    builds b1 join    builds b2 on      b1.buildversion = b2.buildversion + 1         and b1.repid = b2.repid group by         b1.repid 	0.000586655536124389
20626781	5321	join a table based on condition	select    f.id,   case when userkey=0 then l.name else p.name end as username from [feature] f left join [liteuser] l         on condition1 = 1        and l.user_id = f.user_id left join [premium user] p         on condition1 = 2       and p.user_id = f.user_id 	0.00481093263168368
20627277	27371	nexusdb field with spaces ado sql	select "official name" from mytable 	0.573632992475325
20634609	34518	concerning union and join in mysql	select name, city, 'person' as explanation from persons union all select pname, place, 'project' as explanation from projects 	0.731480972062326
20644859	30758	mysql inner join on two tables	select    a.id, a.user_login, b.meta_key, b.meta_value from wp_users a join wp_usermeta b on a.id = b.user_id where meta_key = 'primaryblog'; 	0.163911517923422
20646839	14576	how to get matching pairs of columns in sql	select *   from [mytable]  where (cola = 'a1' and colb = 'b1')     or (cola = 'a3' and colb = 'b3') 	0
20674797	22805	save post data to page indefinitely	select * from yourtable order by id desc limit 1 	0.0228517352191889
20702792	27856	fetching data from sqlite database based on timestamp of present day	select [columns] from [database] where [column_date] < "currentdate"; 	0
20708245	10569	select statement with multiple conditions	select column_id       , sum(case when ammount < 50 then ammount else 0 end ) sumsmall  from t  where ...  group by column_id  having sum(case when ammount < 50 then ammount else 0 end ) > 0      and sum(case when ammount > 50 then ammount else 0 end ) > 0     and sum(case when ammount < 50 then ammount else 0 end ) < 100 	0.483497333546467
20710825	1937	sql compare two colums for same value	select .... , case when scan1 = scan2 then 1 else 0 end as is_equal from table1 	5.32010827644868e-05
20738730	13925	how can i concat these two rows into one column in sql	select id, stuff((select ','+response from tablename b where b.id=a.id for xml path('')),1,1,'') as response from tablename a group by id; 	0.000164390992766518
20741515	37021	mysql select - select avg() query doesn't return when columns does not exist	select m.id_mod, m.module, avg(p.percentaje) from tb_module m  left join tb_activity a on m.id_mod = a.id_mod  left join tb_percentaje p on a.id_act = p.id_act  where m.id_pro = 2 group by m.id_mod 	0.648155381659325
20756837	4483	need a mysql query that can filter the results	select id, chapter_id, question, answer  from (select if(@chapterid=@chapterid:=chapter_id, @id:=@id+1, @id:=0) queno, id, chapter_id, question, answer        from `questions`, (select @chapterid:=0, @id:=0) as a        where `chapter_id` in (19, 20, 21, 22, 23)       order by `chapter_id`      ) as a  where queno < 10 	0.191958786754077
20779417	13215	remove special character from mysql data at search time	select * from tablename where replace(column1, "_","") = 611256 	0.0035478675597634
20780759	34498	what select query will list domains within postgres?	select typname from pg_catalog.pg_type join pg_catalog.pg_namespace on pg_namespace.oid = pg_type.typnamespace where typtype = 'd' and nspname = 'someschema' 	0.29237275986027
20784339	12552	aggregating different column types with group by	select  sum(if(type ='like',1,0) )as likes,              sum(if(type='comment',1,0)) comments,              day(date) 'day'     from `test_types`     group by  day(date) 	0.0116816847770637
20787915	13674	how to use indexes for a query filtering between two columns	select * from autumn.ip where :number-constant >= start order by start desc limit 1 union select * from autumn.ip where :number-constant <= end order by start asc limit 1; 	0.0245431005359983
20796653	30592	mysql group_concat and in query	select t.empid,t.empname,t.empfriendsid,        group_concat(t1.empname) from t left join t as t1 on find_in_set(t1.empid,t.empfriendsid) where t.empid=1 group by (t.empid) 	0.772285280002764
20809275	19470	mysql timediff null values	select (second(a.timestamp_end) - second(a.timestamp_start)) as total_time  from timestamp 	0.0460656093311995
20834027	22149	system.data.sqlclient.sqlexception(date_format)	select convert(varchar(8),getdate(),1) 	0.293983136128189
20837702	21494	how to select random sub string,which seperated by coma(",") from a string	select   slid,   substring_index(     substring_index(adsid, ',', rand()*(length(adsid)-length(replace(adsid, ',', '')))+1),     ',',     -1) as random_ads from   yourtable 	0.000913284424806207
20852479	38471	copy rows from source table to new table given condition	select * into dest from source where source.var="value"; 	0
20867723	33414	pivote table having error	select [gruppi min (gg flusso/decorrenza        sum(case when stato='a2' then 1 else 0 end) as a2,        sum(case when stato='a3' then 1 else 0 end) as a3 from table group by [gruppi min (gg flusso/decorrenza 	0.794358153887753
20870128	28855	mysql return matching other rows when one table returns 0	select   table1.field1,   table2.field2,   table3.field_what from   table1 inner join   table2 on table1.field1 = table2.field1 left outer join   table3 on table3.field2 = table2.field2 where   table1.field1 = 'help' 	0
20872490	33718	load parameter from second mysql table when id equals	select m.id, m.category_id, m.menu_name, m.image_id , i.file_url from menu m  inner join icon i on i.id = m.image_id where m.restaurant_id = '" . (int) $_session['uid'] . "'  and  m.status='1' 	0.000567952949118317
20885660	12872	sql code for sum and max	select article, sum(num_column) from table_name group by article order by article 	0.308659858497633
20887307	35387	select only numbers from varchar column	select replace(columnname,'%','') from tablename where isnumeric(replace(columnname,'%','')) = 1 	0.000129095587572216
20907984	6498	how to check if a sequence exists in my schema?	select object_name   from all_objects  where object_type = 'sequence' and owner = '<schema name>' 	0.163125852906769
20913166	25203	how to show only one piece of data in one column with multiple rows listed in another column	select if(ord=(cnt-1),id,'') id,         if(ord=(cnt-1),title,'') title,        text,        votes from ( select polls.id,         polls.title,         poll_data.text,         poll_data.votes,         case when coalesce(@remain,0) = 0             then @remain:=grouped.cnt-1             else @remain:=@remain-1          end as ord,        grouped.cnt   from polls inner join poll_data            on (polls.id = poll_data.pollid)      inner join            (select pollid,                    count(*) cnt               from poll_data               group by pollid) grouped         on grouped.pollid = polls.id order by polls.id, ord desc) a 	0
20921139	30635	making a select for a two select sql/oracle	select table1.player_id, table1.score score1, table2.score score2,        abs(table1.score - table2.score) difference from (        select player_id, sum(score) score        from (               select player1_id player_id, score_p1 score from matchs               union all               select player2_id , score_p2 from matchs              ) q group by player_id       ) table1 inner join            (             select player_id, sum(score) score             from (                    select player1_id player_id, score_p2 score from matchs                    union all                    select player2_id , score_p1 from matchs                   ) q group by player_id           ) table2 on table1.player_id = table2.player_id 	0.0792354929015115
20927615	24163	mysql: check if var exists in one of two tables	select      if(         (             exists(select name from table_1 where name="")             or             exists(select name from table_2 where name="")         ), 1, 0) as nameexists; 	0.000649094709644228
20931211	7654	listing specific data in query	select    students.studentname,   students.studentnumber,   schools.schooladdress  from   xschools    inner join ystudents      on schools.schoolname = students.schoolname  where schools.schoolname = 'london school' 	0.0480636866823202
20940689	35850	need help combining two mysql queries	select ticketid_pk, subprojectid_fk, projectid_fk, customerid_fk, ticketdate, ticketnumber,  signoff, workorder, clientpo, tickettype, description, processed, (select round(wcb+vacation+stat+uic+cpp+overhead,2) from employeeformula where effectivedate <= ticketdate order by effectivedate desc limit 1) as total from tickets  inner join customerssubprojects on tickets.subprojectid_fk = customerssubprojects.subprojectid_pk  inner join customersprojects on customerssubprojects.projectid_fk = customersprojects.projectid_pk  where ticketid_pk = 1 	0.786430571344405
20953263	31800	count all cases with one mysql statement	select sum( stats = 'open' ),          sum( stats <> 'open' )   from `table`; 	0.0334372634945248
20965726	32573	sql - data reference does not exist when comparing two tables	select artist_name, name, album_genre  from album left join artist on artist.name = album.artist_name and album_genre = artist_genre  where artist.id is null 	0.105340342621741
20968244	25603	mysql query: how can i find top 5 images in each brand ?	select   brand_id,   substring_index(group_concat(image_id separator ','),',',5) as image_ids from table1 group by brand_id 	0.000306416257847942
20968505	15686	mysql, get information using 2 tables	select u.email from wp_users u inner join wp_usermeta um on u.id = um.user_id where um.meta_key = 'app_prefferedcategories' and um.meta_value like '%{"blog_id":"5"}%' 	0.00199461163635876
20978814	1078	mysql get rows that do not match with certain conditions	select * from codes natural join (   select   code   from     codes   where    type in (1,2)   group by code   having   count(distinct type) = 1 ) t 	9.83392824876116e-05
20987099	4832	sql query output months names instead of months numbers	select              year(periodo) as year,       datename(month, periodo) as month,       sum(paid) as paid from                  affitto_sa  group by      year(periodo),      month(periodo) 	4.85977996696498e-05
20988144	36302	inner join two tables, both have foreign keys with no primary key?	select table_1.* ,table_2 from table_1 inner join table_2 on table_1.g_id=table_2.g_id 	0.000118123372857765
21008827	29707	select join multiple rows into single row	select    u1.name borrower,   u1.email,    u2.name lender  from    users u1,    users u2  where    u2.phone='123456'    and    u1.phone='223456' ; 	0.000184539992472316
21011009	3330	php/mysql - schedule appointments underneath proper weekday	select leads.fname,        leads.lname,        leads.addr_city,        appointments.appt_date,        appointments.appt_time,        appointments.id_lead,        d.daydesc from (      select 'monday' as daydesc,1 as dayorder       union select 'tuesday',          2       union select 'wednesday',        3       union select 'thursday',         4       union select 'friday',           5       union select 'saturday',         6       union select 'sunday',           7       )as d left join appointments on (dayname(appointments.appt_date) = d.daydesc) inner join leads on (leads.id = appointments.id_lead) where month(appointments.appt_date) = month(now()) and appointments.id_sales = :id_sales order by d.dayorder asc,appointments.appt_time asc 	0.498106758085652
21013069	20466	mysql left join, get all right table columns and 2 columns from left table based on left table max id	select bs.*, bsp.id as bookseriesphotoid, bsp.ext as bookseriesphotoext from bookseries as bs  left join (select bsp.bookseriesid, bsp.id, bsp.ext             from bookseriesphotos bsp             inner join (select bsp.bookseriesid, max(bsp.id) id                         from bookseriesphotos bsp group by bsp.bookseriesid                      ) as a on bsp.bookseriesid = a.bookseriesid and bsp.id = a.id          ) as bsp on bsp.bookseriesid = bs.id 	0
21018367	9813	getting the create table command used in oracle 11g	select dbms_metadata.get_ddl('table', 'your_table_name_goes_here') from dual; 	0.26276257010697
21019584	39869	list of oracle views using specific table name	select *  from all_dependencies  where type = 'view'     and referenced_type = 'table' 	0.00108472095566845
21039797	36593	multiple search with join	select t1.*, t3.*,t2.* from table3 t3  left join (     select id     from table1     where condition like '%field%') t1    on t3.id=t1.id left join (     select id     from table2     where condition like '%field%') t2 on t3.id=t2.id where t3.id is not null or t2.id is not null 	0.613802119882731
21042133	1919	how to null the repeating column data	select cashgaapyear,        case             when row > 1 then null             else vendorname end as vendorname,        exp1  from (    select cashgaapyear,            vendorname,           exp1,           row_number() over(partition by vendorname,cashgaapyear  order by vendorname  asc) as row     from tablename )  as t 	0.00361205366780192
21043888	33035	mysql select all rows meeting the first and second lowest values?	select * from test where `value` in (    select * from (       select distinct `value`        from test        order by `value`        limit 0,2    ) as t ) 	0
21049661	33984	datagridview sum of same identical rows	select   productid, sum(quantity) as quantity from     mytable group by productid 	0.000183000015004221
21057077	4879	print different values using only select in sqlite3	select name, case healthy when 1 then "eat me" else "avoid me" end from food; 	0.000495007497126093
21061198	13136	sql sorting without using order by	select * from your_table order by case when value < 0 then 1 else 2 end,          memno 	0.546598028460013
21091928	20045	show users that were modified at least 2 times	select u.name from user u inner join userchanges c on c.userid = u.id group by u.name having count(c.id) > 1 and sum(case when changedate >= '2013-12-15' then 1 else 0 end) > 0 	0
21099761	35546	parsing only left side on join	select f_cl_path f,cf.f_id from c_files cf left join (select f_cl_path f, f_id, f_workgroup from myothertable       where f_workgroup ='1234' and f_status<=2) as x on x.f_id=cf.f_id   where cf.f_workgroup='798190' and x.f_id is null 	0.454630470078365
21108382	12675	sql query to retrieve month name from database	select datename(month, invoice_date), sum(r.total) as total from sales r group by datename(month, invoice_date) order by datename(month, invoice_date); 	6.37867843143997e-05
21135687	30619	mssql rownumber wrong row number over datetime which is generated from string	select  row_number() over (       order by dateadd(minute,datediff(minute,0,dateofmeasure),0)) as rownum,  dateadd(minute,datediff(minute,0,dateofmeasure),0) as 'date' from data emd 	0.0104510277839334
21136741	17724	how to group by a column and show as one row	select subid,         listagg(status, '/') within group (order by null) as status from the_table group by subid; 	7.58778334231397e-05
21137722	14222	looping within a stored procedure and filling in a gridview	select  tbla.propertyid as pid,          tbla.propertyname as pna,          tblb.firesafety as firesafety1,          tblb.displayscreenequipment as dse   from    tbpropertydetails as tbla          inner join tbpropertydetailssafeguarding as tblb              on tbla.propertyid = tblb.propertyid  where   tbla.regionid > 0  and     tbla.propertyid like '%' + @propertyid + '%'   and     exists         (   select  1             from    tblpropertyviewpermissions as pvp             where   pvp.employeeid = @employeeid                 and     pvp.propertyid = tbla.propertyid         ); 	0.0956980201037363
21138861	27310	mixing multiple tables into one	select p.*, store_1.quantity as store_1_quantity, store_2.quantity as store_2_quantity from (select product from store_1 union select product from store_2) as p left join store_1 on p.product = store_1.product left join store_2 on p.product = store_2.product 	0.0138922897771204
21148356	35186	select top 3 records from column	select top 3 score from score_table order by score desc 	8.83982511061613e-05
21155856	30783	php / mysql statement so select max sum of join	select name,       sum(counter) as counter from table1 join table2 on table1.id = table2.u_id group by u_id order by counter desc  limit 1 	0.335042620620843
21159863	8643	finding substring from input	select * from tablename where '937089' like concat(num, '%') 	0.0127676789415095
21163556	30436	pivot table for account data with columns for each month	select department_number ,[january] ,[february] ,[march] from ( select department_number, amount, datename(date_created) as month_created from <your_table> ) as sourcetable pivot(sum([amount]) for month_created in ([january],[february],[march])) as pivottable 	0
21169447	5729	pulling distinct values for individuals	select          pct.patient_id,     pct.clinic_id,     pct.axis_i_ii_1,     pct.axis_i_ii_2,     pct.axis_i_ii_3,     pct.axis_iii_1,     pct.proc_chron     from patient_clin_tran pct     join patient p     on p.patient_id = pct.patient_id where p.case_status = 'a'      and pct.proc_chron = (select max(proc_chron) from patient_clin_tran pct2 where pct2.patientid = p.patientid) and (pct.axis_i_ii_1 is not null or pct.axis_i_ii_2 is not null or pct.axis_i_ii_3 is not null or pct.axis_i_ii_4 is not null) order by pct.patient_id 	0.00807012025384584
21173524	21364	only get users with a specific joined table count	select      user.id,     user.name,     item.id as item_id,     itemstatus.item_status,     count(item.status) as status from user join item on (user.id = item.user_id) join itemstatus on (item.status = itemstatus.id) where item.status = 1 group by user.id having count(item.status) >= 3 	0
21178574	7995	selecting records with multiple between clauses	select * from dbo.items where ((postdate between date1 and date2) or (postdate between date3 and date4)) 	0.00198607890945603
21190094	974	getting time series data in qbo 3	select ... from decision   right outer join dbo.timedimensioninterval(@createddatestart, @createddateend, @createddateintervals) as createddaterange     on  decision.createddate >= createddaterange.begindate        and decision.createddate < createddaterange.enddate group by createddaterange.timespan   ... 	0.00652988340630651
21191493	38015	summing over a calculated field of concatenated strings (split acct #s)	select... where... group by right(trim (trailing from (concat('00',cast(t1."gmfund" as char(8))))),3) || '-' || right(trim (trailing from (concat('00',cast(t1."gmdpt" as char(8))))),2) || right(trim (trailing from (concat('00',cast(t1."gmdiv" as char(8))))),2) || '-' ||  right(trim (trailing from (concat('00',cast(t1."gmstab" as char(8))))),2) || right(trim (trailing from (concat('00',cast(t1."gmstas" as char(8))))),1) || '.' || right(trim (trailing from (concat('00',cast(t1."gmelm1" as char(8))))),1) ||  right(trim (trailing from (concat('00',cast(t1."gmelm2" as char(8))))),1) || '-' || right(trim (trailing from (concat('00',cast(t1."gmobj" as char(8))))),2)  order by 1 	0.000565447176021563
21195777	20363	counting items/rows in db as columns grouped by another column	select type       ,sum(case when mydate = '' then 1 else 0 end) as [10/1]       ,sum(case when mydate = '' then 1 else 0 end) as [10/2] from mytable group by type 	0
21200862	32211	get records for each person's each day's min datetime	select a1.* from accesscards a1 join (select name, min(entrydates) mindate       from accesscards       where name != ''       group by name, date(entrydates)) a2 on a1.name = a2.name and a1.entrydates = a2.mindate 	0
21201587	781	postgres column with nulll values and and filtering with "!="	select * from students where status is distinct from 4; 	0.136341496598671
21211432	34241	mysql statement need - select recent message from each user	select m1.*  from `messages` m1 join  (     select m.`from`, max(m.date_creation) as date_creation      from     `messages` m     where m.to = 20     group by m.`from`    ) t on m1.`from` = t.`from` and m1.date_creation = t.date_creation 	0.000124313844568155
21218510	8536	oracle sql extractvalue from multiple elements	select      t.recid     ,t2.value1      ,t3.value2      ,t4.value3  from t inner join xmltable('/row/c1'     passing t.xmlrecord     id_num varchar(4) path 'concat(substring(ancestor-or-self::*/name(.),1,1), @m)',     value1 varchar(20) path '.') t2 on (1=1) inner join xmltable('/row/c2'     passing t.xmlrecord     id_num varchar(4) path 'concat(substring(ancestor-or-self::*/name(.),1,1), @m)',     value2 varchar(20) path '.') t3 on (t2.id_num=t3.id_num) inner join xmltable('/row/c3'     passing t.xmlrecord     id_num varchar(4) path 'concat(substring(ancestor-or-self::*/name(.),1,1), @m)',     value3 varchar(20) path '.') t4 on (t2.id_num=t4.id_num) 	0.0446699167503968
21220340	1026	mysql - return the entire table + count another table	select `forums`.*, count(`topics`.`topic_id`) as `tot_topic` from `forums` left join `topics` on `topics`.`topic_forum_id` = `forums`.`forum_id` group by `forums`.`forum_id` 	0
21220406	8902	how to select last 30 days dates in mysql?	select date_format(m1, '%d %b %y') from ( select subdate( now() , interval 30 day) + interval m day as m1 from ( select @rownum:=@rownum+1 as m from (select 1 union select 2 union select 3 union select 4) t1, (select 1 union select 2 union select 3 union select 4) t2, (select 1 union select 2 union select 3 union select 4) t3, (select 1 union select 2 union select 3 union select 4) t4, (select @rownum:=-1) t0 ) d1 ) d2  where m1 <= now() order by m1 	0
21230730	10151	hide first row in database query	select count(*) as `count`,`lang`, date(now()) as `week_ending` from mydata.table where `date` > date_add(date(now()), interval -1 week) and `date` < date(now()) group by `lang`, date(now()) limit 1,x; 	0.00236927335473876
21235165	35831	android sqlite fts3 match and compare integer/float	select * from mytable where cast(validto as numeric) > 1389999600000 	0.183548641770128
21246442	40420	join two tables and group by problems	select p.`name`, p.`id`, r.`user_id`, sum(r.`value`) as knowledge from `responses` r join `problems` p on r.`problem_id` = p.`id` where r.`user_id` = 4 group by p.`name`, p.`id` 	0.67856624681384
21247791	5386	in mysql how do i pull every 60 enteries in the last hour	select date, private, private2  from miner1  where date >= date_sub(now(),interval 1 hour) and       second(date) = 0; 	0
21248501	26927	sql duplicate record query	select count(1) as frequency, dob from students group by dob having frequency > 1; 	0.0159173656186693
21250408	4155	group multiple rows in listview android	select * from table group by user 	0.136627970189312
21265130	40134	select rows that has mixed charcters in a single value e.g. 'joh?n' in name column	select * from mytable where regexp_like(last_name, '[^a-za-z]'); 	0
21270238	36725	mysql select puzzle	select     *,     timestamp > date_sub(utc_timestamp(), interval 5 minute) as is_online,     userid in (select userid from log) as is_registered from seen_log a join (     select max(id) as max_id     from seen_log     group by userid ) b on a.id=b.max_id where userid in (select followed_userid from following where root_userid = ) 	0.604285326737048
21280930	3239	how to select all rows which have a distinct phone numbers from sqlite?	select phonenumber from yourtable group by phonenumber 	0
21283584	17270	sql server select sum values	select t1, t2, t1 + t2 t3 from ( the query from your question ) temp 	0.0563606013173847
21283889	23467	getting latest entries from the revision table in mysql	select * from revision where id in (   select max(id) from revision group by pageid order by dateupdated desc ) 	0
21304446	9424	transpose the results of a mysql query	select   max(case when t.class_lesson = 'class1art' then t.attendants else null end) as class1art, max(case when t.class_lesson = 'class1history' then t.attendants else null end) as class1history, max(case when t.class_lesson = 'class2geography' then t.attendants else null end) as class2geography from  (  select   group_concat(distinct class, lesson) as class_lesson, count(*) as attendants  from   tablename  group by   class, lesson ) as t 	0.0299597817563923
21304736	24480	mysql - joining two queries (union?)	select year(od_date) as `year`, month(od_date) as `month`, test_name, pd_name,         sum(test_result <= 50) as passed, sum(test_result > 50) as failes from tbl_lab_item li inner join tbl_order_item oi on oi.od_item_id = li.od_item_id inner join tbl_order o on o.od_id = oi.od_id where o.od_date >= date_sub(now(), interval 12 month) and test_name = 'test' and        pd_name = 'product' and od_customer_id = '4' group by test_name, year(od_date), month(od_date) asc 	0.103264222193672
21306091	22424	mysql sort by not sorting?	select * from {$db_sales} where date = '{$date}' order by amount desc 	0.403627403124208
21312666	33622	trim special char from sql string	select case when col like ';%'    then stuff(col,1,1,'') else col end   from dbo.table; 	0.116462156807039
21315161	7994	sql select only rows where a max value is present, and the corresponding id from another linked table	select      tblpartcosthistory.partid,      tblpartcosthistory.partcosthistoryid from     tblpartcosthistory     inner join     (         select             partid,             max(revision) as maxofrevision         from tblpartcosthistory         group by partid     ) as max         on max.partid = tblpartcosthistory.partid             and max.maxofrevision = tblpartcosthistory.revision 	0
21316256	3494	how do i return multiple results from a sql server stored procedure with php prepared statements?	select * from tblprojects  left join  tblpartners  on ( tblprojects.projectid = tblpartners.projectid  ) where tblprojects.projectid = @prjid 	0.620719884609773
21317365	16126	return single value from subquery nested inside a case statment	select teacherid, starttime, endtime,        (case teacherschedulearchice.teacherstudent_servicetypeid             when 0 then ''             else (select top(1) districtname                   from districts                   where district.teacherstudent_servicetypeid =  teacherschedulearchice.teacherstudent_servicetypeid                  )        end) as district from  teacherschedulearchive; 	0.493794946892671
21328384	35598	sql: loop through all columns in a database and alter type	select 'alter table ' + table_name + ' alter column ' + column_name + ' int  ' + case when is_nullable = 'no' then 'not' end + ' null' + char(13) + 'go' from information_schema.columns where data_type = 'bigint' 	0.00240203541832239
21349825	14693	need some help from count query	select count(t.atic)  from app_interview as t, tb_applicants as t2  where t.atic = t2.aic  group by t.atic; 	0.695620048421022
21359769	29365	mysql psuedo column in where cluse	select id , days from  (  select p.id as id , datediff(now(),p.startdate) as days  , p.status as status  from poa p  )  t where t.status < t.days; 	0.188439733090762
21372424	19983	query to find unique value for the combinations	select id_col  from table  group by id_col  having    count(0) = 2 and   count(case when value_out in (11,12) then 1 end) = 2 	6.79332613557515e-05
21416671	25833	sql to extract list of values given a xmlstring (oracle)	select x.myid from xmltable('/xml/*'   passing xmltype(' <xml>     <myid>1</myid>     <myid>2</myid>     <myid>3</myid> </xml>')   columns myid path '/myid') x; 	9.25410400307301e-05
21441765	10139	comparing interval of date with sql	select * from reservations  where datedebut <= '2014-01-29' and datefin >= '2014-01-12' and idproduit = 320; 	0.0104342700289815
21447258	169	get date/time at local timezone	select state       ,to_char(          localtimestamp          at time zone            case state            when 'qld' then 'australia/queensland'            when 'act' then 'australia/act'            when 'tas' then 'australia/tasmania'            when 'nsw' then 'australia/nsw'            when 'nt'  then 'australia/darwin'            when 'sa'  then 'australia/adelaide'            when 'wa'  then 'australia/perth'            when 'vic' then 'australia/victoria'            end         ,'hh24:mi') as local_time from custorders; 	0.0188754880629144
21454817	32016	query changes in mysql records	select id, status, user_id, created_at from  (select id, status, user_id, created_at,          (case when @user_id != user_id then 'true' else 'false' end) as user_changed,          (case when @status  != status then 'true' else 'false' end) as status_changed,          (case when @user_id != user_id then @user_id := user_id end) as new_user_id,          (case when @status  != status then @status := status end) as new_status   from (select * from logs order by user_id asc, created_at desc) l    join (select @user_id := 0) u    join (select @status := 0) s) q where user_changed = 'true' or status_changed = 'true' order by id ; 	0.0655401446781758
21456137	1471	loop for taking element if other = 1 (from a row)	select * from acc where loggedin = "1" 	0.000149911582946561
21463300	19677	sql query mysql to json	select t.team as stats, (select sum(t1.eurocups) from cups t1 where t1.team_id = 3) as value1, (select sum(t2.eurocups) from cups t2 where t2.team_id = 1) as value2  from cups c  join team t    on c.team_id=t.team_id where c.team_id = 3 or c.team_id=1 group by t.team 	0.560839728739631
21468019	40069	sql creating a concatenated string of names from an array of ids	select prj.name, tsk.id as task_id from project_table prj   join (       select id, regexp_split_to_table(projects, ',')::int as pid      from task_table   ) tsk on tsk.pid = prj.id order by prj.id 	0
21490100	29333	need a query to count number of times a customer visits each region	select account_number,region,count(*) as nbr_visits from mytable   group by account_number,region 	0
21495433	28292	sql - select rows that their child rows's column contains specific string	select r.routeid, s.stopname from route r inner join stop s on r.stopid = s.stopid where routeid in   (select t1.routeid from route t1   where exists (select * from stop s2 where t1.stopid = s2.stopid and s2.stopname = 'stop_1')) order by r.routeid, s.stopname 	0
21496702	8998	sql, finding other entries based on them having one attribute in common the same	select b.bookid  from   author a         inner join author b on a.authid = b.authid and a.bookid <> b.bookid where  a.bookid = 52; 	0
21505025	5706	add one year, to a year in the where clause	select * from event where year(year) >= ? and year(year) <= ?+1 	0.000195398473545037
21505082	10822	mysql information from another table	select a.roleid , a.deity_level, b.name from default_jd_deity_role as a join default_jd_ingame_roles as b on a.roleid=b.roleid limit 10 	0.000574216546908658
21524840	13188	ordering table by hour	select *  from  table1 order by case when hour > 17 then -1               else hour          end 	0.0136231376444832
21526058	40955	convert rows to string in postgresql	select string_agg(name1, ',') as name1s from t1 	0.0173719828612334
21538049	2328	hive date format handling	select unix_timestamp(regexp_replace('mon 2014-01-03 13:00:00 +gmt0000','gmt',''),                       "eee yyyy-mm-dd hh:mm:ss z") as unixtime from reqtable; 	0.768998964626258
21539938	32957	is it possible to take multiple mysql tables, then form a php array?	select p1.key,p1.username,p1.password, p2.phone,p2.addr,p2.addr2,p2.facebook,p2.linkedin,p2.twitter,p2.youtube from social_profiles t1 join address p2 on p1.memberid = p2.memberid where p1.key = $memberidhere 	0.0055860395658234
21561607	14983	sql - assorting data	select       contacts.name,     emails.email from  cont_email inner join contacts  on cont_email.name_id = contacts.id inner join emails on cont_email.email_id = emails.id order by contacts.name; 	0.193602337797447
21568314	21262	mysql select from t1 where id in t2 not present in t3	select       t1.title,       t1.data    from       youralerttable t1          left join alreadyviewedtable t3             on t3.t2id = theuseridparameterwhologgedin             and t1.id = t3.t1id    where       t3.t2id is null 	0.00413666493745815
21572161	33832	cartesian join on country and swimmer tables, but exclude labeled countries	select swimmername, "fr" from swimmerlist where fr<>"n" union select swimmername, "ne" from swimmerlist where ne<>"n" union select swimmername, "be" from swimmerlist where be<>"n" 	0.0193528981554885
21576152	36885	in sql how to change null values in a view	select bankno, isnull(cast(branchno as nvarchar(10),'no branch') from banktable 	0.0376227098106133
21578882	474	sql group by year+month, but get months w/o records too	select dt.theyear, dt.themonth, sum(t1_count) from datetable dt left outer join table1 t1   on dt.theyear = t1.t1_year   and dt.themonth = t1.t1_month group by dt.theyear, dt.themonth 	0.0048621114844208
21583797	17531	sql date mm_yyyy	select replace(right(convert(varchar(10), getdate(), 105), 7),'-','_') 	0.12845287785115
21590476	34188	joining the column outputs of two or more columns from a mysql query	select * from (select * from table_0) as x     left join (select * from table_1) as y on 1; 	0.00010897575982027
21598387	5730	one query for multiple where?	select     round((         sum(case when antwoorden.coach_id = 0 then score else 0 end) /         sum(case when antwoorden.coach_id = 0 then 1 else 0 end) * 10     ), 1) as score_0,     round((         sum(case when antwoorden.coach_id = 1 then score else 0 end) /         sum(case when antwoorden.coach_id = 1 then 1 else 0 end) * 10     ), 1) as score_1 from antwoorden join vragen     on vragen.id = antwoorden.vraag_id join categorieen     on categorieen.id = vragen.categorie_id where antwoorden.werknemer_id = 105 and antwoorden.coach_id in (0,1) group by categorieen.id 	0.110629596534871
21600708	19295	sqlite: create view to multiple tables via index	select access.date, ips.ip, machineids.machineid, platforms.platform, platforms.os, apps.application, apps.buildnum, access.responsecode  from access     left join ips on access.ip_id = ips.id     left join machineids on access.machineid_id = machineids.id      left join platforms on access.platform_id = platforms.id     left join apps on access.application_id = apps.id 	0.176538411879227
21608033	10249	assigning specific return value from multiple return values to a variable	select top 1 @return = thm.name from theme thm left join producttheme pdt on thm.pk_theme = pdt.themeid left join storyproducttheme spt on pdt.pk_producttheme = spt.productthemeid left join story sty on spt.storyid = sty.pk_story where sty.number = @storynumber     and thm.name in ('adaptive','corrective','perfective','preventive','new development') order by      case thm.name when 'adaptive' then 1                   when 'corrective' then 2                   when 'perfective' then 3                   when 'preventive' then 4     else 6 end 	4.7995606697246e-05
21611000	21727	mysql: how many times a value appear in each line	select (a = 12) + (b = 12) + (c = 12) + .... + (f = 12) as twelves ... having twelves >= 3 	0
21611560	24021	join just last record in second table, but include records don't have match in second table	select cs.*, o.* from customers cs left outer join (   select customerid, max(orderid) as orderid from orders   group by customerid ) lnk on cs.customerid = lnk.customerid left outer join orders o on lnk.orderid = o.orderid order by cs.customerid 	0
21613469	17552	access sql max-function	select process_title as title        , max_version.max_version_no        , c.version_status as status from (parenttable p inner join (select max(version_id) as max_version_no, version_fk_process_id from childtable group by version_fk_process_id) max_version     on p.process_id = max_version.version_fk_process_id) inner join childtable c     on max_version.max_version_no = c.version_id and max_version.version_fk_process_id = c.version_fk_process_id 	0.644822827086622
21620860	20648	how to get column value which define in another table	select t1.workid as 'workid',t1.question as 'question', coalesce(`field1`,`field2`,`field3`,`field4`,`field5`) as 'answer' from table1 as t1 join table2 as t2 on t1.workid = t2.workid 	0
21624913	30602	retrieve data from 2 fields with a count from one of them	select sales_location, group_concat(countries_name), count( * ) from countries group by sales_location 	0
21635970	11479	how to write a report query based on number of days in a month?	select id,name,address,trans_dt from tab1 where trans_dt between trunc(trunc(sysdate,'mm')-1,'mm') and trunc(sysdate,'mm'); 	0
21641068	11181	oracle pivot function with two columns	select     department_id,      sum(case when salary = 1000 then 1 else 0 end) as salar_equal_1000,     sum(case when salary = 2000 then 1 else 0 end) as salar_equal_2000,     sum(case when city   = 'boston' then 1 else 0 end) as city_boston,     sum(case when city   = 'detroit' then 1 else 0 end) as city_detroit,     sum(case when city   is null then 1 else 0 end) as city_none from     employees group by department_id order by department_id 	0.293920794340066
21644306	35690	use between between two like	select * from my_table where name_column >= 'a' and name_column < 'k'; 	0.0878646670788169
21665364	32388	joining tables preserving order with possible multiple occurrences	select t1.ord1,max(t2.ord2)ord2,t1.col1 from table1 t1 join table2 t2 on t1.col1=t2.col2 and  t1.ord1>=t2.ord2 group by t1.ord1 	0.0451992119896135
21671052	4806	mysql group by max id & left join another table	select * from   posts p1 join (select album_id, max(post_id) post_id from posts group by album_id) p2   on p1.album_id = p2.album_id and p1.post_id = p2.post_id 	0.00826567093341566
21682197	29646	finding last record in a day	select * from  (    select t.*,       row_number()       over (partition by fk_sales_rep_id              order by invoice_date desc) as rn    from tab as t    where cast(invoice_date as date) = '12/31/13'  ) as dt where rn = 1 	0
21682912	30114	append string value to int column	select a.sales, sum(a.count) as count, 'month ' + convert(varchar(20), dt.cumulativemonth) from rep a inner join date dt on a.date = dt.fd group by dt.cumulativemonth, a.sales 	0.00279199987159688
21707326	2892	i want to join 3 tables and aggregate records of two columns from 2 of those tables while avoiding record duplication	select tablea.id, tablea.name, b.b_val, c.c_val from tablea left join (select tablea.id as id, sum(coalesce(tableb.val,0)) as b_val from tablea left join tableb on tablea.id = tableb.a_id group by tablea.id) as b on tablea.id = b.id left join (select tablea.id as id, sum(coalesce(tablec.valc,0)) as c_val from tablea left join tableb on tablea.id = tableb.a_id left join tablec on tablec.b_id = tableb.id group by tablea.id) as c on tablea.id = c.id 	0
21720219	19952	group and choose max pair sql	select k.person, k.fruit from (   select person,fruit,count(fruit) as cnt   from txns   group by person,fruit ) k join (   select t.person,max(t.cnt) mxcnt   from   (     select person,fruit,count(fruit) as cnt     from txns     group by person,fruit   )t group by t.person ) s on s.person = k.person and s.mxcnt = k.cnt  order by k.person 	0.0524011914051095
21721948	15440	existence of a value - performance efficient in sql	select 'found it' from example_table where artikel='radio' limit 1; 	0.218375307886135
21736184	21611	how to select the value duplicated the least number of times in sql	select top 1  facilityid,count(servername) over (partition by facilityid) as cardinality from tablename order by cardinality asc 	0
21741631	11540	calculate running balance in mysql select query and view	select m.`mat_id`, m.`mat_name`, m.`stock_in`, m.`stock_released`,        (select sum(stock_in) - sum(stock_released)         from material m2         where m2.mat_name = m.mat_name and               m2.mat_id <= m.mat_id        ) as balance,       m.`date` from `material` m order by m.`mat_id` asc; 	0.208142261763431
21778686	1841	oracle select distinct return many columns and where	select distinct a.* from temp_ids a join (select name, max(col1 || ' ' || col2  || ' ' || col3) id from temp_ids where col1 = 2 group by name ) b on (a.name = b.name and (col1 || ' ' || col2  || ' ' || col3) = b.id) ; 	0.0101866697770676
21786799	8894	filter word starting with /	select substring_index(name, '/', -1) as foo from table1; 	0.135548053437895
21787852	29262	detecting date overlaps without going day by day	select r1.id, r2.id from rentals r1 join rentals r2 on r1.car_id = r2.car_id and r1.id != r2.id where (r1.start_date < r2.end_date or r2.end_date is null) and r1.end_date > r2.start_date; 	0.00041965074644606
21794772	19938	between two datestime in mysql	select * from `field_data_field_dateres`  where field_dateres_value  < '2014-02-14 20:30:00'    and field_dateres_value2 > '2014-02-14 20:15:00'; 	0.0225373566155331
21801326	41029	selecting in sql server 2008	select * from [mytable] where id in    (select max(id) as id from mytable group by name) 	0.273900983699195
21829786	40210	postgresql count in multiple coulmn	select agent,         count(customer) as total_customer,         count(case when january_1 <> 0 then 1 end)  as sales_customer from salestable  where customer_type = "urban" group by agent  order by agent asc 	0.112393779392628
21830476	10346	mysql : get latest value and sum of values from previous hour	select p.id, max(date_created), sum(value), mv.max_value from product p join values v on p.id = v.product_id join (select product_id, value as max_value       from values v2       where date_created = (select max(date_created) from values where product_id=v2.product_id)) mv on product_id=p.id where date_created between date_sub(now(), interval 1 hour)) and now() group by p.id order by p.id 	0
21832170	28887	selecting distinct data from all columns but 1	select agg_article_title,agg_article_link,agg_article_media,agg_article_description,agg_article_source_name, agg_source_tag_tag_name, agg_source_url   from agg_article    join agg_source    on agg_article_source_name = agg_source_name    join agg_source_tag    on agg_source_name = agg_source_tag_source_name    where agg_source_included = 1    group by agg_article_title, agg_article_link 	0
21837003	5944	mysql computed column	select  u.id,          u.username,          sum(s.test_score) totaltestscore from    users u left join         scores s on u.id = s.user_id group by    u.id,              u.username 	0.0334791838396314
21839947	11161	sql query to retrive data	select p1.productname from product p1, myorder s1, lineitem l1, customer c1 where l1.pid=p1.pid and l1.oid=s1.oid and c1.cid=s1.cid and c1.city='mycity' group by p1.productname having count(distinct c1.cid)=(select count(1) from customer c2 where c2.city='mycity'); 	0.0981866316741704
21850480	10188	unpivot from existing query	select 'completed turnover' description,          (  '£'+ cast(sum(rc.[fee charge] +                      rc.[fee charge vat] +                       rc.extracharges+                      rc.extrachargesvat+                      rc.othercharges+                      rc.otherchargesvat+                      rc.waitingcharge+                      rc.[waitingcharge vat]                    )as nvarchar(50))) value from .... union all select 'in progress turnover', ..... from .... union all select 'unallocated turnover', ..... from .... 	0.165091544453431
21869731	38489	sql : file name	select *     from sys.sysfiles     where name like'[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%' 	0.136842085862223
21873541	15133	how can i get the intersection of the multi-select sentences in mysql?	select code_co.code from code_co            left join note on note.code = code_co.code           where note not in           (select distinct note from note           where note like '%cholera%' or note like '%diarrhea%" or note like '%fever%') 	0.00588710168961622
21885267	13839	how to find longest string in the table column data	select top 1 cr from table t order by len(cr) desc 	0
21891602	7137	access query using * and sort criteria on columns - how to make field show just column name?	select projects.* from projects order by projects.mysortfield desc; 	5.80300874525387e-05
21904611	5916	list by project_id using queries	select project_id ,substring_index(group_concat(employee_id),',',1) as employee_id1,substring_index(substring_index(group_concat(employee_id),',',2),',',-1) as employee_id2, substring_index(substring_index(group_concat(employee_id),',',3),',',-1) as employee_id3, substring_index(substring_index(group_concat(employee_id),',',4),',',-1) as employee_id4 from my_table group by project_id; 	0.15189335098405
21911371	26826	mysql join table with 2 id's	select  u1.name as user1,  u2.name as user2 from matches inner join users u1 on u1.id = matches.user_1 inner join users u2 on u2.id = matches.user_2 	0.00408056873944323
21925946	36342	mysql if select count() is greater that zero select * from table else return nothing found	select * from table_xx where column_xx = (   select column_xx from table_xx    where column_xx = value_xx group by column_xx having count(column_xx) > 0 ) 	0.00145784627713834
21926832	17819	joins in mysqli for fetching multiple tables data	select u.id,         u.userid,         u.name,         u.mobile,         (select count(*)          from   follow f          where  f.followerid = u.userid) as follower,         (select count(*)          from   follow f          where  f.followeeid = u.userid) as followee  from   users u 	0.186078936991988
21927229	28833	how can i count how many people in table a?	select count(distinct name) from a mytable 	0.00302355697793941
21927349	21604	how to measure selectivity for composite index	select count(*) / sum(c) from    (     select col1, col2, ... coln, count(*) c     from table     group by col1, col2, ... coln   ) 	0.759604176917599
21930263	2362	combine single date record with multiple time slot	select      name,      dateadd(second, datediff(second, 0, starttime), eventdatetime) startdatetime,      dateadd(second, datediff(second, 0, endtime), eventdatetime) enddatetime from eventtable a inner join slotstable b on a.eventid=b.eventid 	0.000103519254183081
21933322	41291	sql server : group, create columns and sort by week	select  *     from     ( select [player], [week], [score]         from    temp_db) as sourcetable     pivot     (         avg([average])         for [week] in ([2013w51], [2013w52], [2014w1], [2014w2])     ) as pivottable; 	0.00129895570722588
21943107	10504	fetching one to many relationship from same table	select customer_id,    listagg(subscription_name, '; ') within group (order by subscription_name) as subscription_name from subscription group by customer_id order by customer_id; 	0
21944997	18108	filter by column alias (firebird sql)	select dis from   (select distancemeters("latitude_c_", "longitude_c_", 44.894115, -123.031717) as dis     from curr_location) where dis < 5000 order by dis 	0.456940862351703
21958852	29848	failed to get columns result from db using 'like' in sqlite3 android ?	select fatwa.question_id,question.ques_img_name from fatwa,question  where  fatwa.fatwa_keywords like '%hadees%' and fatwa.question_id =question.id 	0.0961143654458502
21960732	10852	sql compare data pairs	select x.name as name1, y.name as name2, x.title as movie from actedin x join actedin y on x.title = y.title where x.example_pay > y.example_pay 	0.00401581479208734
21962822	40386	query sum value from two tables	select     f.family_id,     f.father_name,     f.mother_name,     f.last_name,     cp.children_count,     isnull(cp.children_payment,0) + isnull(fp.families_payment,0) sumpayment from dbo.families f     inner join  (                 select                     c.family_id,                     count(distinct c.child_id) children_count,                     sum(p.payment_value) children_payment                 from dbo.children c                     inner join childrenpayments p                         on p.child_id = c.child_id                 group by                     c.family_id                 ) cp         on cp.family_id = f.family_id     inner join  (                 select                     p.family_id,                     sum(p.payment_value) families_payment                 from familiespayments p                 group by                     p.family_id                 ) fp         on fp.family_id = f.family_id 	0.000518503337007311
21969498	23555	mysql selecting data from table2 where table1.field is equal (and add it on to the result)	select p.*,        case          when w.license_number is not null then           w.license_number          when s.premises_license_number is not null then           s.premises_license_number          else           null        end as profilelicense_number   from profiles p   left join studios s     on p.profile_id = s.profile_id   left join workers w     on p.profile_id = w.profile_id 	8.71910135985693e-05
21978911	17893	subtraction in sql server 2008	select count(i.ward_id) - w.bed_strength as diff from  ip_admission i join ward_master  w on w.ward_id=i.ward_id where (status='v' or status='d') and i.ward_id=1 group by w.bed_strength 	0.775143537719643
21987570	9954	mysql - how to join those tables to get the correct result?	select s.product_name, sum(number_purchases), price from sales s, prices p where s.product_name = p.productname and customer_id = 80 group by s.product_name; 	0.000940893070788567
21994802	36786	mysql query for extracting names separated by ";" and check if it is selected in combobox	select name from yourtable where storename like '%yourchoice%' 	0.000152559723630946
21996390	20647	double quotes appearing in a string within select sql statement	select  [qtr], [year], [gl_bu]   from dbo_ttbl_admin_rxrebate  where ([qtr] = 'q3') and ([year] = '2013') and ([gl_bu] = 'b50931')   strrecsetquery = ""  strrecsetquery = strrecsetquery + "select  "  strrecsetquery = strrecsetquery + "[qtr], "  strrecsetquery = strrecsetquery + "[year], "  strrecsetquery = strrecsetquery + "[gl_bu]  "  strrecsetquery = strrecsetquery + "from dbo_ttbl_admin_rxrebate"  strrecsetquery = strrecsetquery & " where ([qtr] = '" & strqtr & "') "  strrecsetquery = strrecsetquery + "and ([year] = '" & stryear & "') "  strrecsetquery = strrecsetquery + "and ([gl_bu] = '" & strgl_bu & "');" 	0.532883887843102
21997795	20395	return all ids where the count in table1 is equal to the count in table2	select * from (  select id, count(*) as n         from specific_files         group by id) as p inner join (select id, count(*) as n             from all_files             group by id) as k     on p.id = k.id     and p.n = k.n 	0
21997818	35547	missing rows when selecting from 2 tables	select     aid.itemid,     count(ah.itemid) as "total",     aid.stack from      ahbot_item_data aid     left outer join auction_house ah     on (aid.itemid = ah.itemid and aid.stack = ah.stack) group by     aid.itemid, aid.stack 	0.00013121388515862
22002693	27563	how to delete non duplicate rows in mysql?	select e.ssn, e.fname, e.lname, d.dependent_name, d.sex, d.relationship  from employee e join      dependent d       on e.ssn = d.essn join      (select d.essn, count(*) as cnt       from dependent d       group by d.essn       having cnt >= 2      ) d2      on e.ssn = d2.essn order by e.ssn; 	0.000801086156821696
22005762	16881	count rows in each 'partition' of a table	select y, count(*) from (   select y,          sum( xyz ) over (             order by id             rows between unbounded preceding             and current row          ) qwe   from (      select *,             case              when y is null and                  lag(y) over ( order by id ) is null                  then 0             when y = lag(y) over ( order by id )             then 0              else 1 end xyz      from table1   ) alias ) alias group by qwe, y order by qwe; 	0
22009447	30869	mysql - how to get last record using group by	select * from dept_activities as da1 join (select max(id) as max_id from dept_activities group by deptid desc) as da2 on (da1.id = da2.max_id); 	4.87111031416224e-05
22016334	1599	mysql and php: select all fields from the same date	select  id,  date,  site,  url from links  where publish = "yes"  and    date = ( select date from links where date < '2014/02/25' order by date desc limit 1 )   and category!= 'adult'  order by date desc, clicks desc limit 200 	0
22020036	32766	sql query to divide a value over different records	select col1,(  (select sum(col2 )    from tab   where col1 =1000)   /   (select count(*)     from tab    where col1 =500))+col2 as new_value   from tab  where col1=500 	0.00050550212731884
22030975	10650	how to find fields with calculating other fields?	select temp_table.name as nameofperson  from   (select cust.name,                 count(distinct restaurant) as uniquerest          from   visits,                 cust          where  cust.name = visits.name                 and cust.gender = 'female'          group  by cust.name) as temp_table  where  uniquerest >= 2 	0.00023030322592795
22037777	713	extract values from in parameter and store it in local variables in postgresql	select substring(listdate from '............$') as v_end_date, substring(listdate from '^...............') as v_start_date 	0.0324103119016938
22038464	32465	linking one table with continuous dates to another non-continuous	select * from continuoustable c inner join splittable s on s.fs_perm_sec_id = c.fs_perm_sec_id where s.split_date =      (     select max(s2.split_date)     from splittable s2     where s2.fs_perm_sec_id = c.fs_perm_sec_id     and s2.split_date <= c.date     ) 	7.45295746475153e-05
22039602	28038	how to retrieve sql table records for specified date range	select * from tablename where month(dob) between 1 and 3 	0
22062211	3161	mysql query for one-to-many relation and only-one-row return	select userproducts.*,         topquery.*   from userproducts,         ( "here the query from the top ) topquery  where .. 	0.316181324697299
22062649	19877	(sql server) using row count to sort the list but dont need list out the row count number	select a.station, c.aging from                        (select station, row_number() over (order by totalseq asc) as rownumber1      from [sfckm].[dbo].[t_db_subline] where track_point_no = '3d1') a     left join     (*,aging,row_number() over (order by commit_time desc) as rownumber     from [sfckm].[dbo].[t_work_actual] where track_point_no = '3d1') c on a.rownumber1 = c.rownumber order by a.rownumber1 	0
22065408	17547	search by special characters	select description from tablename where decription like '\%test' 	0.514439349418145
22066725	8379	conversion in sql server	select convert(varchar, cast(123456 as money), 1) 	0.724886065268831
22070409	15702	select from where not in - except	select       p.id,       p.photo    from       photos p          left join cats c             on p.photo = c.photo             and c.cat = 'p'    where           p.user = 40000       and c.photo is null 	0.0967007263844843
22071851	7461	time between two non consecutive rows? (mysql)	select t1.animal_id,         t1.testdate,        (select min(testdate)         from exams         where animal_id = t1.animal_id           and testdate > t1.testdate         group by animal_id         ) as next_testdate,          datediff((select min(testdate)                   from exams                   where animal_id = t1.animal_id                     and testdate > t1.testdate                   group by animal_id                   ), t1.testdate) as elapsed_days from exams t1 order by animal_id, testdate; 	0
22077709	37856	select top record with sharing column's value sql server	select            id, shift_id, name_of_shift, person_in_shift,     starttime_in_shift, endtime_in_shift, table_id,     startdate, enddate, point_id from                sarcshifttable where id in  (  select min(id)  from sarcshifttable  group by table_id ) 	9.72529342996573e-05
22099934	12424	how can i get data from two different tables	select * from inventario inv, materials mat on inv.fk = mat.id 	0
22103888	21318	sql-ex.ru execise 14	select distinct maker, type  from product  where maker in     (select distinct maker      from product      group by maker having count(distinct type) = 1     and count(model) > 1) 	0.441351244561316
22114282	36413	select columns from two different table with different fields in one query access database	select discount , price from tbl_discount, tbl_tariff where d_id = ? and p_id = ? 	0
22129986	14239	multiplying values from different tables	select s.staffid,         h.date,         h.hours * s.wage as amount from staff s inner join hours h on h.staffid = s.staffid 	0.000120719126733322
22151956	4202	is it possible to export an sql queries results into a document from the client side	select sale, del into outfile 'c:/tmp/orders.csv' fields terminated by ',' enclosed by '"' lines terminated by '\n' from order; 	0.0238404412803329
22158355	14435	get records with most recent timestamp and also with proper grouping	select *  from  (    select tab.*,        rank() over (partition by phone order by order_time desc) rnk  ) dt where rnk = 1 	0
22161526	17055	order by with sum, min, max, etc using ebean	select id,name,tickets from users  where tickets is not null order by ticket desc 	0.2383924048128
22176886	5204	third highest salary in mysql without using max or min function	select * from salaries order by amount desc limit 2,1;                                          offset  	0.00346340362705322
22178883	17935	selecting from multiple tables where a condition is true	select d.firstname,     l.lat,     l.lng from driver_details d     inner join locations l on d.user_id = l.user_id where l.lat between 0 and 5     and l.lng between 0 and 5 	0.0031607908982314
22179900	21961	count rows from multiple joined tables - mssql	select catthread.categoryname, catthread.categorydescription,     catthread.numberofthreads,     count(posts.id) as numberofposts from     ( select category.id, category.name as categoryname, category.description as categorydescription,     count(threads.id) as numberofthreads     from category       left join threads on threads.fkcategoryid = category.id     group by  category.id, category.name, category.description) catthread     left join threads on threads.fkcategoryid = catthread.id     left join posts on posts.fkthreadid = threads.id group by catthread.categoryname, catthread.categorydescription,     catthread.numberofthreads 	0.000329233143574878
22183358	18315	how to do a two table sql select	select a.alpha       ,a.zeta       ,b.alpha       ,b.zeta from tablea a inner join tableb b  on a.alpha   = b.alpha 	0.00637110728803312
22186737	21389	mysql - select distinct 2 columns and return all	select unique_id, model, color, slots from table_name group by model, color 	8.92169911013167e-05
22192701	36960	how can i use pivot table on sql server with adventureworksdw database	select   firstname,              lastname,              englishproductname,              [2001],              [2002],              [2003],              [2004] from     (     select   cus.firstname,              cus.lastname,              prod.englishproductname,              sum(sale.orderquantity) quantity,              tar.calendaryear yil     from dimproduct as prod              inner join factinternetsales as sale on sale.productkey = prod.productkey              inner join dimtime as tar on tar.timekey = sale.orderdatekey              inner join dimcustomer as cus on cus.customerkey = sale.customerkey     group by cus.firstname,              cus.lastname,              englishproductname,               calendaryear ) as gtablo     pivot     (     sum(quantity)     for yil in ([name],[2001],[2002],[2003],[2004])     )     as p     order by firstname 	0.619774474258717
22194703	449	how to count multiple columns in a mysql query	select   count(t.ticketid) as totaltickets,  sum(case when t.status='open' then 1 end) as totalopen,  sum(case when t.status='close' then 1 end) as totalclose ,(     select count(*) from tbl_ticket t      left join tbl_ticket_reply tr on t.ticketid=tr.ticketid ) as total_replies from tbl_ticket t 	0.0112518544426399
22202248	34822	counting the number of male & females from tables	select    student_class.acad_yr,   case when students.gender='male' then count(students.gender) end as male,   case when students.gender='female' then count(students.gender) end as female from   students   inner join student_class on (students.st_id = student_class.st_id) where   student_class.acad_yr = '2013/2014' and    left(student_class.class_id, 1) = '1' group by   student_class.acad_yr order by   students.surname,   students.othername 	0.000149860195219033
22206379	31242	count values over m/n connected tables in sql	select n.id,        n.name,        count(distinct l.id) as locations,        count(distinct d.id) as downloads from names n left join names_location nl   on n.id = nl.name_id left join downloads dl   on n.id = dl.name_id left join locations l   on l.id = nl.location_id group by n.id, n.name 	0.0208136949161183
22225035	16815	how to set priority for search value	select `course`.`id`, `course`.`name`   from `course`   where `name` like 'teb lorem ipsum' or         `name` like '%teb%' or         `name` like '%lorem%' or         `name` like '%ipsum%' order by case when `name`='teb lorem ipsum' then 1 else 2 end asc 	0.00962776662498867
22228669	37997	unknown column in fieldlist for a timestamp column	select `time`   from transactions; 	0.013821956163114
22233567	25612	get result in a one hour interval	select x.*   from my_table x   join      ( select max(dt) max_dt          from my_table         group by date(dt),hour(dt)     ) y    on y.max_dt = x.dt; 	9.7715888911588e-05
22239070	24857	sql view/query to return sum by current month	select sum([sales total]) as sales,     salesperson,     year(date) [year],     month(date) [month] from dbo.[sales by salesperson] where year(date) = year(getdate()) and month(date) = month(getdate()) group by salesperson, year(date), month(date) 	0.000218190410266201
22250125	7195	how to use alias name of inner query as a column to get record that have no data or is null in sql query?	select sq.subcategoryname,     sq.subcategoryid,     sq.imagename from (     select subcategoryname,         subcategoryid,       (select top (1) image          from postimage         where (postdesignid like (                                     select top (1) postdesignid                                       from postdesign                                      where (subcategoryid = sc.subcategoryid)                                            or (subcategoryid2 = sc.subcategoryid)                                   )                )        ) as imagename    from subcategory as sc  ) as sq where sq.imagename is not null 	0.00156911009581837
22270999	4704	group by top two results based on order	select a.name, a.ord_n, a.ord , a.f_id  from    (     select      rank() over (partition by f_id order by ord asc) as "rank",      row_number() over (partition by f_id order by ord asc) as "ord_n",      help.*     from help   ) a where a.rank <= 2 	0.000334851088420383
22291114	26324	percentage is equal to zero	select 'data'     ||','||to_char(d.dtime_day, 'mm/dd/yyyy')     ||','||nvl(g.ticket, 0 )     ||','||case when nvl(h.employee,0) = 0 then 0                  else round((nvl(g.ticket,0) / h.employee),2) end     ||','||nvl(h.employee,0)     ||','||case when nvl(g.ticket,0) = 0 then 0                  else round((nvl(h.employee,0) / g.ticket),2) end     from owner_dwh.dc_date d <rest of statement> 	0.0350950411134357
22301811	5675	average of character fields?	select cust, sum(case when ordertype = 'phone' then 1 else 0 end) * 100 / count(*)  'phone percentage', sum(case when ordertype = 'phone' then 0 else 1 end) * 100 / count(*) 'internet percentage' from table1  group by cust 	0.00200973647583257
22308410	28094	how to determine most often element in postgresql?	select element from table1 group by element order by count(*) desc limit 1 ; 	0.00761384459183525
22312672	37165	postgresql case when date and sorting by date	select   id,   coalesce(closedate, resolveddate) as finaldate from   cases where   (extract (month from coalesce(closedate, resolveddate)) = extract(month from current_date)) and   (extract (day from coalesce(closedate, resolveddate)) = extract(day from current_date)) 	0.35644768437045
22314419	16356	php/mysql total by member	select `id`, `player`, sum(`hours`) as hours, sum(`minutes`) as minutes from `$tbl_name` group_by `player`; 	0.00275972587723943
22322445	37398	how can i order the result after i've used limit?	select a.* from (select * from yourtable order by date desc limit 4) a order by a.date 	0.259276950340238
22348854	40275	mysql nearest row before with another column having a specific value	select *,     (select t2.uid      from test t2      where stabilisation=1 and t2.created <= t.created      order by t2.created desc limit 1) as t2_id from test t order by t.created; 	0
22354077	19053	want to show one highest scorer details grouped by every month	select x.*   from my_table x   join       ( select date_format(date,'%y%m')yearmonth             , max(score) max_score           from my_table          group             by date_format(date,'%y%m')      ) y     on y.yearmonth = date_format(x.date,'%y%m')    and y.max_score = x.score; 	0
22355708	35013	count number of text coincidence in all columns of a row	select      (if(pos1 like 'var%', 1, 0) +     if(pos2 like 'var%', 1, 0) +     if(pos3 like 'var%', 1, 0) +     if(pos4 like 'var%', 1, 0) +     if(pos5 like 'var%', 1, 0) +     if(pos6 like 'var%', 1, 0)) as done from customize where id = 'core2' 	0
22363816	9786	how to get year just before current year from mysql table	select t.* from table t where year(aca_start_date) = year(now()) - 1 limit 1; 	0
22376323	20046	distinct for only one column and other column random?	select case when rn > 1 then null else col1 end,col2     from     (     select *,row_number() over(partition by col1 order by col1) as rn     from yourtable     ) as t 	0
22387411	6295	how to use another query in an in statement?	select code  from table.status  where reference in (    select sec_code    from table.sec_status    where sec_reference = 'abc'    union '423'  ) 	0.379725237677175
22391417	30954	group results by day and month (php timestamp) showing total revenue per day	select date_format(from_unixtime(`timestamp`),'%d') day, date_format(from_unixtime(`timestamp`),'%m') month, sum(`revenue`) from sales group by day,month order by month,day 	0
22393781	7703	how to join counts dependent on outer groups	select   mid,   sum(if(oid is null,1,0)) as oid_null,   sum(if(oid is not null,1,0)) as oid_not_null from tablename group by mid 	0.247372861714172
22404046	40058	mysql ignore null results after first occurrence	select * from (select * from `lastviewed` where `user_id` = 266 and record_id is not null  union select * from `lastviewed` where product_id not in (select product_id from `lastviewed` where record_id is not null group by product_id) ) as q1  group by product_id, record_id order by `lastviewed` desc  limit 4; 	0.00172568334041838
22413095	34829	how to group rows based on min value of the column in sql server 2008	select id,     name,     sum(price) as price,     groupid,     groupname (        select id,                name,                sum(price) as price,                groupid,                groupname,                key,                row_number() over (partition by id, groupid order by key) as rna         from #tmptable         group by id, name, price, groupid, groupname, key  ) as a  where rna = 1  group by id, name, price, groupid, groupname 	0
22417876	30853	oracle db order tree siblings by sibling linked list	select distinct wut.root,    listagg(wut.data, ' ')     within group (order by wut.polishorder)     over (partition by wut.root) polish from         ( select connect_by_root(n.id) root, data, rownum polishorder  from nodes n  join  (select m.id, level l   from nodes m   start with m.siblingnode is null   connect by prior m.id = m.siblingnode) mm  on n.id = mm.id      start with n.parentnode is null      connect by prior n.id = n.parentnode      order siblings by mm.l ) wut 	0.421953730148662
22431197	5323	mysql complex select with just one table	select lead_id      , max(case when field_no =  5 then value end) firstname      , max(case when field_no =  6 then value end) lastname      , max(case when field_no =  3 then value end) telephone      , max(case when field_no = 12 then value end) number   from my_table  group      by lead_id; 	0.101073024310237
22434336	37789	how to find the last quarter in mysql	select quarter(curdate() - interval 1 quarter); 	4.96198110683607e-05
22466120	4984	selecting and grouping from two mysql tables	select date,        max(case when name='fb' then value else null end) as fb,        max(case when name='twtr' then value else null end) as twtr,        max(case when name='ftse100' then value else null end) as ftse100   from (select date, index_name as name, value from index_table         union         select date, stock_name as name, value from stock_table)         as derivedtable  group by date 	0.000346894242094591
22490347	10312	combining select distinct with group and ordering	select f1.name,f1.count from fruit f1 inner join (select name,max(datep) date_p from fruit group by name) f2 on f1.name = f2.name and f1.datep = f2.date_p order by f1.name 	0.14336461422901
22512839	31868	php/mysql: 2 selects from same table in one query	select b.user, a.value as "user1val", b.value as "otheruservalue" from st as a       join st as b       on a.user = "user1" and a.user != b.user  where     (b.value > (a.value - 3)) and (b.value < (a.value + 3)) 	0.000131007152832773
22526929	11343	sql get max value	select filterid from (   select filterid,           viewid,           rank1,          max(rank1) over (partition by viewid) as max_rank   from filter ) t where rank1 = max_rank; 	0.00415239040919302
22539552	36622	how to find count of a field based on range of 10 values	select per_year.year, sum(per_year.count) as total_decade from hindi2_movie inner join      (select count(*) as count, year from hindi2_movie group by year) per_year on hindi2_movie.year >= per_year.year and hindi2_movie.year < per_year.year + 10 group by hindi2_movie.year 	0
22555617	20601	error selecting rows where decimal > 0	select * from ( select emplid, empl_rcd, dz_presence_type, dz_date, sum(dz_time_hours) hours from ps_dz_time_vw  group by emplid, empl_rcd, dz_presence_type, dz_date ) a where a.hours > 0 	0.0942907764872427
22623512	39015	adding a summed field to a select query	select *, sum_query.sum_field from table join (select sum(field) as sum_field from table) as sum_query 	0.0102652686829421
22629179	4700	i need to create a query for comparing two columns in same table	select internal_id,        plan_id,        numerator,        sum(numerator) over (partition by internal_id,plan_id order by (select null)) as denominator from table1 	0.000229353952903918
22632246	3275	mssql select distinct and sorting	select vers, revs  from (     select max(date_deployed) as d, vers, revs      from tblmver      where mid = 194      group by vers, revs      order by d desc, vers desc, revs desc ) as temp 	0.183559296469802
22635558	31405	optimise query to determine of a value is between a min and max value	select * from table where 36 between min and max; 	0.00161967678954065
22638590	15253	sum and format combined mysql	select format(sum(cost), 2)  from table; 	0.0868783055908779
22642893	21371	the query with start and end date	select name, service,  min(dates) as mindate, max(dates) as maxdate, country, sum(price) as price from dbo.table where country is not null and service in ('incoming', 'outgoing') and years =2014 and months=3 group by name, service, country 	0.0111695428901502
22655765	26781	mysql result set concatenation column wise	select * from (select 1,2) t1 join (select 5,6) t2 union  select * from (select 3,4) t1 join (select 7,8) t2 	0.0265881048673128
22659223	16054	multiple sql queries in one result	select     isnull(sum(ps.unitssold), 0) as unitssold,     isnull(pg.[description], 'other') as [description]     sum(case when (ps.orderdate between getdate() - 10 and getdate() - 3) and ps.distributioncentreid = 3 then 1 else 0 end) as unitssoldthisweek      sum(case when (ps.orderdate between getdate() - 17 and getdate() - 10) and ps.distributioncentreid = 3 then 1 else 0 end) as unitssoldthisweek      sum(case when (ps.orderdate between getdate() - 374 and getdate() - 367) and ps.distributioncentreid = 3 then 1 else 0 end) as unitssoldthisweek  from dbo.productsales ps left outer join dbo.product p on ps.productid = p.productid left outer join dbo.productgroupings pg on p.[asin] = pg.[asin]  group by pg.[description], ps.distributioncentreid 	0.0451384845908721
22663656	24891	sql: unioning 2 tables and then joining on another. is there a better way of doing this?	select  table1.timestamp as timestamp,      table1.zid,      table1.aaa as responses,     'aaas' from table3  left join table1 on table3.id = table1.zid union select  table2.timestamp as timestamp,      table2.zid,     table2.aaa as responses,     'bbbs' from table3 left join table1 on table3.id = table2.zid order by timestamp asc; 	0.0372777927867496
22672145	11250	sql/python - multiple selects and calculating within sql	select players.first_name, players.last_name,   sum(case events.event         when 'single' then 1         when 'double' then 1         when 'triple' then 1         when 'home run' then 1         else 0       end)   / count(events.event) as avg from mlb.events join mlb.players on mlb.players.player_id = mlb.events.batter where team_id = %s group by events.batter order by mlb.events.batter 	0.175899691409376
22677765	12735	how to join two sql select statements side by side	select kernel.dog_id, d.name as dog , c.name as cat from appointment a left join animal d on  kernel.dog_id=d.animal_id; left join animal c on  kernel.cat_id=c.animal_id; 	0.289298746835369
22682629	29416	mysql: get count for records on a certain date and overall	select    count(word) as all_count,    count(if(`date`=curdate(), word, null)) as today_count  from    t  where    word='word1' 	0
22687491	19686	after joining three query not getting proper result in sql server	select sum(status_receved) as receved, sum(status_parked) as parked, sum(status_requested) as requested from (select case when (status = 0) then 1 else 0 end as status_receved, case when (status = 2) then 1 else 0 end as status_parked,  case when (status = 3) then 1 else 0 end as status_requested  from transaction_tbl where locid = 6 and status in (0,2,3)) a; 	0.739949582419036
22695015	3536	how to determine if null is contained in an array in postgres?	select exists (     select 1      from unnest(array[1, null]) s(a)     where a is null );  exists   t 	0.0881517679713284
22708152	2715	displaying a value if it doesn't exist?	select distinct(w1.wind_dir) as dir, ifnull(ws/10,0) as speed from weather w1 left join ( select windspeed as ws, wind_dir as wd from weather w2      where w2.windspeed/10 < 0.5       and w2.date>=now()-interval 1 day ) wth on w1.wind_dir=wd; 	0.0721014646844913
22718238	30659	conversion of string having date format with am/pm to dd-mm-yyyy hh24:mi:ss format	select to_date('3/03/2014 6:00:28 am','dd/mm/yyyy hh:mi:ss pm')  from dual 	0.00760616200791768
22718543	11186	sql query - link to lookup where lookup field may be null	select ther_id     ,isnull(code_name,'no code found') [codename] from therapy t left join ref_code r     on t.prot = r.code where event_id = 1234     and r.cat_id = '1'; 	0.736079363216305
22720378	5428	group by not returning correct totals	select sum(totalsales) totalsales, sum(tsalesaftcomm) tsalesaftcomm,        sum(numofsales) numofsales, saledate from (   select       emp_id,       sum(salea+saleb) as totalsales,       sum(salea+saleb-comma-commb) as tsalesaftcomm,       count(emp_id) as numofsales,       saledate   from sales (nolock)   where saledate>='2014-03-15 00:00:00'   group by saledate, emp_id   having       sum(salea+saleb) > 10000 ) z group by saledate order by saledate 	0.771119467731134
22725676	30817	sql display info with max(count(*))	select g.firstname, g.lastname, count(*) as hella from   guest    g join   timeslot t using (timeslotnum) join   shows    s using (shownumber) where  s.showname = 'fitness' group  by 1,2 order  by 3 desc limit  1; 	0.0569459137843814
22735912	38939	comparing values from two different tables in sql plus oracle	select firstname, secondname from doctor, job, hospital where hospital.name = 'hospitalname'  and job.hospital_id = hospital.hospital_id and job.doctor_id = doctor.doctor_id; 	6.58313005296248e-05
22737761	27307	mysql query joining data from several tables	select      distinct(s.stop_id),     s.stop_name,     r.route_short_name from stops s       inner join stop_times st on st.stop_id = s.stop_id      inner join trips t on t.trip_id = st.trip_id      inner join routes r on r.route_id=t.route_id  where r.route_short_name='42' group by s.stop_id; 	0.00438862694636395
22743683	28809	get all comments including its votes for a post	select commentid,comment_content,count(*) as total from comments inner join comment_votes on (comment_votes.comment=comments.commentid) where post={$postid} group by commentid; 	0
22748316	22942	how to copy structure and data with specific column in visual foxpro	select col1,col2,col3,col4,col5,col6,col7,col8,col9,col10 from table1 into table table2 	0.0251309919327563
22755095	19014	if minute is less than 60 then remove hour part from result	select @average =     case    when convert(int, @hour) <> 0 then convert(varchar(9), convert(int, @hour)) + ':'    else ''    end +       right('00' + convert(decimal(10,0), convert(decimal(18,2), @mns)), 2) + ':' +    right('00' + convert(decimal(10,0), convert(varchar(10), @second)), 6) 	4.54712631756225e-05
22760573	8721	how to select the max value in mysql in varchar field	select * from testtable where substring(test,2)=(select max(cast(substring(test,2) as signed)) from testtable); 	0.000499159528829608
22765518	28909	mysql getting the most recent entry from two database tables	select c.clientid, count(c.clientid), c.account_name, c.created_date, c.cert_verified, n.noteid, n.note_date, n.note_body  from clients c, notes n  where c.clientid = n.clientid and   n.noteid in (select max(nm.noteid) from notes nm where nm.clientid = c.clientid)  group by c.clientid asc 	0
22774030	5502	how to select from table with conditions from other table	select words.id, words.word, category.name from words join link on link.wordid = words.id join category on category.id = link.catid where category.name = 'badwords' 	0
22774484	12873	postgres query: ranking posts by users based on user activity	select name, topic.id as topic_id, count(*) as total_arguments from     argument a     inner join     topic t on t.id = a.topic     inner join     users u on u.name = t.creator where name = _name group by name, topic.id order by total_arguments desc 	0.000172006530707953
22776354	18930	replace a column data with data from another column in the same table mysql	select id as cat from yourtable 	0
22788019	33456	solved - sql - return all records for an account based on comparison between records for that account	select * from   mytable where  account in (select ext.account                    from   mytable ext                    inner join (select account, date                                from mytable ext                                where open_amount = 0                                   or open_amount < gross_amount) sub                               on ext.account = sub.account                               and ext.date < sub.date                    where  open_amount > 0) 	0
22790678	31379	sum of working days with date ranges from multiple records (overlapping)	select "employee_id",        sum( "work_end_date" - "work_start_date" ) from(   select "employee_id",          "work_start_date" ,          lead( "work_start_date" )               over (partition by "employee_id"                   order by "employee_id", "work_start_date" )           as "work_end_date"   from (      select "employee_id", "work_start_date"      from table1      union      select "employee_id","work_end_date"      from table1   ) x ) x where exists (    select 1 from table1 t    where t."work_start_date" > x."work_end_date"      and t."work_end_date" > x."work_start_date"       or t."work_start_date" = x."work_start_date"      and t."work_end_date" =  x."work_end_date" ) group by "employee_id" ; 	0
22803673	22256	how do i obtain data from three tables in mysql?	select * from gallery_items  right outer join gallery_album_items  on gallery_items.id=gallery_album_items.id  left outer join  gallery_tags  on gallery_tags.id   =  gallery_album_items.id      where gallery_items.name like '%{$term}%'  or gallery_items.description like '%{$term}%' or gallery_tags.tag like '%{$term}%' 	0.00126723895797386
22805006	26638	use a formla on sql server column values and store it in new column	select      count(*) as responsecount,     propertyvalue as answer ,  convert ( dec(28,2) ,count(*))*100/(sum(count(*)) over ()) as responsepercentage from      table  where      questionid = 42 and formid = 1  group by      propertyvalue 	0.00823619784209461
22821388	22363	calculate round(avg) from same table and join	select users.fname, users.userid,users.usertype from users   left join (select round(avg (ratings)) as rating_avg,userid from  vendor_rating group by userid order by rating_avg desc ) ven  on users.id=userid  where users.usertype='vendor' order by rating_avg desc 	0.000497020884214614
22832081	18147	sql: exclude row if value in both columns	select *  from table_name  where login <> alias 	7.88464646870895e-05
22840268	40281	sql count all ocourence pr date	select   to_date(datetime, 'yyyy-mm-dd'),          count(case when initials is not null then 1 end) as answered,          count(case when initials is not null and response_time between 0 and 30 then 1 end) as answered_within_30_sec from     ks_drift.v_webdesk_servicecenter where    datetime between '2014-03-19' and '2014-04-01' group by to_date(datetime, 'yyyy-mm-dd') 	0.00751063777719052
22853500	25698	get the date difference in milliseconds in oracle	select ((extract(day from time2-time1)*24*60*60)+  (extract(hour from time2-time1)*60*60)+ (extract(minute from time2-time1)*60)+ extract(second from time2-time1)) *1000 as millisecs from dual; 	0.000467919611539505
22854687	38364	finding the 3rd highest salary in mysql without limit	select *    from one one1    where ( 3 ) = ( select count( one2.salary )                    from one one2                    where one2.salary >= one1.salary                  ) 	5.31482519823384e-05
22855552	19533	subquery with ties	select book_id, title, year_publd from bkinfo.books where book_id =     (     select top 1 book_id     from bkorders.order_details     order by quantity*order_price desc     ) ; 	0.701199339484949
22856786	21775	join two tables on 2 conditions	select distinct c.id, c.modif, c.value from table1 c join table2 o on o.id = c.id  where c.modif not in (   select o.modif from table2 o ) 	0.00812703123458917
22867092	1693	show count(*) column for value 0 in multiple rows	select content.* ,  (   select count(*)    from votequestion   where idquestion = content.id ) as votes from content where type = 'question' order by contentdate limit 30 	7.3099315485434e-05
22867592	19698	unable to update sql via a view with tableadapter	select * into surveypage1 from surveypage1_view where 1=2 	0.654846098012984
22869372	33654	get min price id without inner select	select t.id, t.parent_id, t.price from table t left join table t2   on (t.parent_id = t2.parent_id and t.price > t2.price) group by t.id, t.parent_id, t.price having count(*) = 1 and max(t2.price) is null order by t.parent_id, t.price desc; 	0.00107475675886579
22870319	34959	mysql : outer join query : some alternate better approach (overriding field value by other table's field value only if available)	select temp.account_id, temp.prfl_param_id,if(param_value is null,temp.param_default_value,param_value) dfd from (   select a.account_id, pp.prfl_param_id, param_default_value   from account a, profile_parameters pp  ) temp left join account_profile ap on temp.account_id=ap.account_id and temp.prfl_param_id=ap.prfl_param_id 	0.000457755233019847
22873364	27396	how to get max value with some case in pl/sql	select job_type,job_name,yes_no,max(task no) from table where  yes_no='y' group by  job_type,job_name,yes_no union select t1.job_type,t1.job_name,t1.yes_no,max(t1.task no) from table t1   left join (select distinct job_type,job_name              from table where yes_no = 'y'             ) t2     on t2.job_type = t1.job_type     and t2.job_name = t1.job_name where t2.job_type is null group by  t1.job_type,t1.job_name,t1.yes_no 	0.0175932923218327
22874431	12862	get the start and end of the day in timestamp in mysql	select    date_format(concat(curdate(), ' 00:00:00'), '%m/%d/%y %h:%i:%s') as morning,   date_format(concat(curdate(), ' 23:59:59'), '%m/%d/%y %h:%i:%s') as evening 	0
22891357	28102	mysql: where not like '%(select column_name from table_name)%'	select column_name from table_name where not like (select concat('%', column_name, '%') from table_name) 	0.412426661804149
22902513	16789	get results only with max change?	select item, price1, price2, ((price2 - price1)/price1) * 100 as my_output from table group by item, price1, price2 having ((price2 - price1)/price1) * 100 = (select( max(((price2 - price1)/price2) * 100)) from table) 	0.00228347052926481
22911324	29003	how to decrease query execution time with distinct?	select distinct on ( topic_category_id ) * from topic t     where post_time >= abstime(now ( ) - 24 * 3600 )     order by topic_category_id, post_time desc limit 10; 	0.660647325268549
22913995	16960	avg of sum in sql	select    b1_cod,    sb1030.b1_desc,    sum(b2_cm1) as sum_cm1,    sum(b2_qatu) as b2_sal,    sum(b2_qatu * b2_cm1) as b2_val,   sum(b2_qatu) / sum(b2_qatu * b2_cm1) as new_field from sb1030  inner join sb2030 on b1_cod = b2_cod where b1_tipo = 'pa' and b2_qatu <> '0' group by b1_cod, sb1030.b1_desc order by b1_cod, sb1030.b1_desc; 	0.124627822484392
22914576	37117	sql the next nearest record	select a.name, a.id as eat_id, min(b.id) as sleep_id from act_detail a left outer join act_detail b  on a.name = b.name and b.action = 'sleep' and b.id > a.id where a.action = 'eat' group by a.name, eat_id order by a.id; 	0.00104292215861508
22915456	1660	sql query conditional on results of another query	select *     from data    where matchid in (select matchid from match where datekickoff='10/08/2013') 	0.134762395547455
22923016	7783	how do i accumulate arrays into maps?	select cookie,    union_vector_sum( keyword_map),    union_vector_sum( map( fqdn, 1 ) ),    collect_set( pixel) from (   select cookie, fqdn, pixel,          collect( keyword, 1 ) as keyword_map   from t   lateral view explode( keywords ) k as keyword   group by cookie, fqdn, pixel ) xk group by cookie; 	0.0233618293948064
22925238	37056	how do i join into a table based on two separate fields on the input and one field on the join table?	select ca.to,        co1.name as toname,        ca.from,        co2.name as frname from contacts co1 inner join calls ca on co1.[#] = ca.to inner join contacts co2 on co2.[#] = ca.from 	0
22938219	28581	mysql table data select on to field one have reference of other	select case when col2 is null then col1  else col2 end as col from (select  @first as col1,@parent_id :=     (     select id     from    mytable     where   parent_id = @parent_id     ) as col2 from    (     select @parent_id := @first     ) var2,     (     select  @first := 7     ) var1 straight_join     mytable where   @parent_id is not null)tab 	0
22953661	10488	many to many query with 3 tables	select *  from  (select * from was w left join was_user wu on w.id=wu.wasid) tmp left join user u on tmp.userid=u.userid 	0.0971193242101756
22958479	12310	get row number using where clause	select * from (select @rn:=@rn+1 as rank, user, score   from scores,   (select @rn:=0) t2 order by score desc) t where user=2 	0.00714469372313475
22959284	10192	how can you decide which records of a joined table remains after a group by?	select u.*,p.* from users u left join  ( select userid, max(value) as max_value from purchases group by userid) p on u.userid = p.userid 	0.000329080449186294
22960672	18384	create mysql view with an extra calculated field in table	select *,time_to_sec(timediff(now(), latest_time_seen)) as secs_diff from tbl 	0.0433352554893257
22973338	24937	sql query to generate an extra field from data in the table	select    person,    cost,    fromdate,    coalesce((select min(fromdate) from tbl1 later where later.fromdate > tbl1.fromdate), '2099-01-01') as todate  from tbl1 order by person, fromdate; 	0.000608029021508817
22980088	10958	how to search two mysql tables using ones data	select m.id from maintable as m join categoriestable as c on c.other_table_id = m.id where c.category in (6, 12) and m.country = 5 	0.00485121011525429
22983055	32258	t-sql select values from the end of a string which are between 2 characters	select reverse(substring(reverse(colname),2,charindex('a',reverse(colname),2)-2)) from yourtable 	0
22987812	17105	limit number of root entities in doctrine query, but allowing any number of joined entities	select a.id from article a limit 10 select a, c from article a left join a.comments c where a.id in (4, 8, 15, 16, 23, 42, ...) 	0.000782277062070989
22990343	20829	oracle : how to order hexadecimal field	select str from t order by to_number(str,'xxxxxxxxxxxx'); 	0.285135497932506
22991173	31099	retrive phone numbers from customer	select  replace(telnr,'-', '') as telnr  from    ringupp where   (telnr like '%$p1%' and '$p1' <> '') or      (telnr like '%$p2%' and '$p2' <> '')  or      (telnr like '%$p3%' and '$p3' <> ''); 	0.000143123079059007
22993834	24723	sql server: rows to columns with case	select id,   max(case when seq = 1 then clid else 0 end) client1,   max(case when seq = 2 then clid else 0 end) client2,   max(case when seq = 3 then clid else 0 end) client3,   max(case when seq = 4 then clid else 0 end) client4 from (   select id, clid,     row_number() over(partition by id order by id) seq   from prop_cl ) s group by id; 	0.094773017809595
22997279	15275	sql query needs to return rows even when results are null	select u.name, c.[description], hs.duration from users u cross join categories c left outer join hourlystats hs on u.userid = hs.userid and c.eventid = hs.eventid 	0.0270846042414756
23005309	17084	mysql first result before and after result set	select      * from   `measurements` `m1`   where       `m1`.`cowid` in (23 , 22, 19, 18, 17, 16, 15, 20, 21, 14)     and `m1`.`cellcount` >= 0     and (`m1`.`date` between ifnull((select                  max( `m2`.`date`)             from                 `measurements` `m2`             where                `m2`.`cowid` =  `m1`.`cowid`                     and `m2`.`date` < '2014-03-28 00:00:00'),         '2014-03-28 00:00:00') and ifnull((select                  min( `m3`.`date`)             from                 `measurements` `m3`             where                 `m3`.`cowid` =  `m1`.`cowid`                     and  `m3`.`date` > '2014-04-11 23:59:59'),         '2014-04-11 23:59:59'))   order by  `m1`.`cowid` asc ,`m1`.`date` asc 	0.00286470296994114
23006307	4280	how to have two nested queries inside one select statement?	select tp.l# from truck t inner join trip tr on tr.reg# = t.reg# inner join tripleg tl on tl.t# = tr.t# and tl.departure = 'melbourne' where t.reg# = 'pkr768' 	0.0948820143819509
23006359	1097	sql query to comparing the minutes in sql 2008 r2 server	select *from table where datepart(hh,yourdatefield)>=17 and and convert(date,yourdatefield,103)='2014-04-03' 	0.284281590424411
23014412	28358	result in single row	select  sum (case when parameterid = 'ava (vti)' then (resultvalue) else 0 end) as 'ava (vti)', sum(case when parameterid = '2d/ao root diam' then (resultvalue) else 0 end) as '2d/ao root diam' from dbcreators.parameter as p where parameterid  in ('ava (vti)', '2d/ao root diam') 	0.00641053675635275
23024836	30942	how do i pivot in sql without columns?	select counttype, mycounts from   (select      count(case when ipaddress0 like '10.172.%' then 1 else null end) as hw     ,count(case when dnshostname0 like '50%' then 1 else null end) as hn   from v_network_data_serialized) p unpivot   (mycounts for counttype in     (hw, hn) ) as up; 	0.125488517501719
23025041	3694	working with a date in sql	select e.student_id   from courses c, class_enrollment e  where to_date(to_char(sysdate, 'dd-mon-rr')) - c.end_date <= 30; 	0.693885558912002
23028736	1177	how to distinct limit for every data	select distinct(prod_code) as code, (select product_stock.purchase_tax from product_stock where product_stock.prod_code = code order by id desc limit 1) as purchase_tax from product_stock where prod_code in ( 5300,  'bluebook' ); 	0.0039262626167873
23053544	33208	selectively populating result column	select ta.c1 as columna,         coalesce(tb.c1, tc.c1) as columnb        from tablea ta, tableb tb, tablec tc 	0.0545543905859722
23055434	36227	finding date and time of last 5 days	select  key,date_format(lastupdated, '%d %m %y')  from    table  where   date(lastupdated) between now() - interval 5 day and now()  order by key desc; 	0
23055484	2316	filtering sql data with multiple filter vb.net (winform)	select col1, col2, col3   from tablex  where col3='10/20/20' and (col1 like '%/x/%' or col1 like '%/y/%') 	0.319177549662865
23068710	3213	sql query against "bad word" filter list	select count(*) from badwords where @username like '%'+thebadword+'%' 	0.420839288007847
23074641	8519	select max value from group	select temp.departmentid, temp.sickleavehours as maxsick, eh.employeeid from (select h.departmentid departmentid, max(e.sickleavehours) sickleavehours from hr.department d, hr.employeedepartmenthistory h, hr.employee e where e.employeeid = h.employeeid and d.departmentid = h.departmentid and h.enddate is null group by h.departmentid) temp, hr.employeedepartmenthistory eh, employee emp where eh.departmentid = temp.departmentid and emp.sickleavehours = temp.sickleavehours and emp.employeeid = eh.employeeid 	0.00264413216296185
23090401	5506	first and last row_number for each partition	select pr.ssn as ssn,  max([earliest last name]), max([latest last name]), min(pr.address) as [address],  min(pr.city) as [city],  min(pr.state) as [state],  min(pr.zip) as [zip], min(cast(pr.[pay begin period] as date)) as [pay begin period], max(cast(pr.[pay end period] as date)) as [pay end period], from (select pr.*,   first_value([last name]) over(partition by ssn order by [pay begin period]    range between unbounded preceding  and current row) as [earliest last name],   last_value([last name]) over(partition by ssn order by [pay begin period]    range between current row and unbounded following) as [latest last name]   from payroll.dbo.[table1] pr  ) pr where (cast(pr.[pay begin period] as date) > '1/1/2013' and     cast(pr.[pay end period] as date) < '12/31/2013') group by pr.ssn; 	6.07847250904013e-05
23111784	4504	how can i display the email of the user who has booked	select     `bookings`.*,     `users`.`email` as booking_email from `bookings` left outer join `users`     on (`bookings`.`user_id` = `users`.`id`) where         `room_id`   = '".$room_id."'     and `eventdate` = '".$datetocompare."'     and `timeslot`  = '".$time."' 	0
23113117	3722	unable to sum a particular column values with multiple distinct columns	select itemname, costrate, sum(quantity) from product group by itemname, costrate 	0.000115549206452844
23120024	14012	how to verify if fields are matching in two tables using sql	select a.* from table1 a left join table2 b on a.city = b.city and a.state = b.state and a.zipcode = b.zipcode where b.zipcode is null 	0.000210038766183783
23121552	38321	returning the 4 most recent orders for each customer	select customerid, orderdate from orders as extorders where orderid in (      select top 4 orderid      from orders      where customerid like extorders.customerid      order by orderdate desc) order by customerid;  	0
23127753	40659	why i cannot select from some selected results?	select * from ( select * from dbo.[sometable] ) as x 	0.347063333695696
23131917	31544	sql query get most wanted game details	select top 1 f.game_name, f.game_platform, g.cover_img,         count(f.game_name) as cnt from   games g inner join        favourites f        on g.name = f.game_name  group by f.game_name, f.game_platform, g.cover_img order by count(f.game_name) desc; 	0.063503854299524
23138391	23763	sql server : pivot on non aggregate field - employee hierarchy	select  * from (select [level],employeename from dbo.getemployeehierachy(myid)) as sourcetable pivot ( max(employeename) for [level] in ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10]) ) as pivottable; 	0.101249643525967
23164600	31795	how do you add all the values of a particular column from mysql db using php?	select sum(_balance) from a where .... 	0
23184135	23536	ordering based on the total of a related table in mysql	select playername ,totalhits from players p inner join ( select player_id,sum(hits) as totalhits from games group by player_id ) as g on p.id=g.player_id where p.team='yankees' order by totalhits desc 	0
23193066	29725	mysql temporary table	select *,sum(x_media) from (select monto, #obtengo el campo monto (select count(*) from tbl_layout_c ) as total_datos, #contar los registros (select sum(monto) from tbl_layout_c ) as suma_total, #suma total (select max(monto) from tbl_layout_c ) as valor_maximo, #valor maximo (select min(monto) from tbl_layout_c ) as valor_minimo, #valor minimo (select suma_total / total_datos) as promedio, #promedio (select monto - promedio) as x_media #media artimetica from tbl_layout_c)tablealias 	0.100529207360841
23193306	37584	select company_id for duplicated fields in mysql	select a.company_id,b.company_id as duplicate_company_id from company_table a, company_table b where a.id != b.id and a.company_id != b.company_id and (     a.ph_no = b.ph_no     or     a.mobile_no = b.mobile_no     or     a.email = b.email ) 	0.0270819586021155
23197383	33859	create table using select query in sql server	select   * into #tempabc from (   select 'a' [test]   union   select 'b' [test] ) a select * from #tempabc 	0.325141193707346
23200050	21813	select data from multiple tables in same query	select `category_name`,  `category_slug`  from  `blog_categories`, `blog_post_categories`  where `blog_categories`.`category_id` = `blog_post_categories`.`category_id`  and `blog_post_categories`.`post_id` = 1 	0.000598830223621299
23201826	16467	count items with 3 tables	select c.cat_id, c.title as cat_name, p.prod_id, p.title as prod_name,        count(*) as cnt,        100*count(*)/cat_total as pct from products as p inner join user_products as up on p.prod_id = up.prod_id inner join (select c.cat_id, c.title, count(*) as cat_total              from categories as c              join products as p on c.cat_id = p.cat_id              join user_products as up on up.prod_id = p.prod_id              group by c.cat_id) as c on c.cat_id = p.cat_id group by p.prod_id order by cat_name, cnt desc 	0.00538653374393323
23202764	20364	concatenating multiple fields in one record sql	select user, month, group_concat(event), sum(gross) from xyz group by month 	0.000606171509633393
23205741	39292	how do i generate add foreign key statements for a group of tables?	select concat('alter table ', table_name,               ' add foreign key (', constraint_name, ')',               ' references ', referenced_table_name,               '(', referenced_column_name, ');' as alter_cmd from information_schema.key_column_usage where referenced_table_name is not null; 	0.000149361932341909
23220501	41200	sum over values by month in milliseconds	select strftime('%y-%m', date / 1000, 'unixepoch') as month,        sum(value) as sum from entry group by 1 	0.000479318762177287
23239250	31889	how can i get last revision_id of particular event_id?	select event_id, max(revision_id) from mytable group by event_id 	0
23257404	38313	join/merge 3 tables with count	select  a.pid,         a.name,         count(distinct b.tid) talkingpoints,         count(distinct c.fid) facts from    people a         left join talkingpoints b             on a.pid = b.pid         left join facts c             on a.pid = c.pid group   by a.pid, a.name order   by a.pid 	0.0827189805858206
23267824	23514	how to retrieve current week data in mysql?	select * from table_name where yearweek(date(field_name), 1) = yearweek(curdate(), 1) 	0
23268296	6042	mysql - how to let 3 row data become 1 row data	select     remark,    sum(totala) as totala,    sum(totalb) as totalb,    sum(totalc) as totalc from the_table group by remark 	0.000113564345820471
23290361	31150	generating a new id based on max-value in database	select ifnull(max(ordreid),0)+1 from bestilling 	0.00149973653801886
23304554	27614	sql join multi tables	select     v.`name` from     `values` v     inner join  `fieldvalues` as fv         on v.`id` = fv.`valueid`         and fv.`fieldid` = 4 union select     v.`name` from     `values` v     inner join  `formcustomizevalues` as fcv         on v.`id` = fcv.`valueid`         and fcv.`fieldid` = 4 	0.426514293300885
23333529	12959	mysql: selecting value, which is not in db	select     min(my_column) from     my_table where    my_column + 1 not in (select my_column from my_table)    and my_column > 2000    and my_column < 3000 	0.0124403031315679
23336429	11566	select distinct columns sql server	select * from (     select *, row_number() over (partition by cnum, cuid order by id) as rownum      from con ) x where x.rownum = 1 	0.0327999500665419
23345506	16498	error: all queries combined using a union, intersect or except operator must have an equal number of expressions in their target lists	select  td = 'acero', '', td = convert(int,sum(totalprice)/b.xchgrate/1000),'', 	0.756874306783266
23347782	4811	sql query to get results that match between three tables, or a single result for no match	select  t1.date, t1.queueid, s.fromdate, s.todate, s.campaignid from      table1 t1      left join       (         select              t2.queueid,             t3.fromdate,             t3.todate,             t3.campaignid         from             table2 t2               inner join              table3 t3 on                  t2.spid = t3.spid      ) s on          t1.queueid = s.queueid and         t1.date between s.fromdate and s.todate 	0
23358597	7185	setting dynamic values for dropdown filters	select id, group,convert(date, summary_date) as summary_date from application where  group='" + selectedgroup + "' and summary_date <=dateadd(year,1,getdate()) order by id, summary_date 	0.706574364882571
23360162	36626	select clause with if condition	select ae.message, re.name, re.surname from addedevents ae left join registered re on ae.id_person=re.id_person 	0.684541485989386
23361486	13074	calculate the credit amount the employee	select (select sum(money1) from t1 where job_id='8') -         (select sum(money2) from t2 where job_id='8') 	0.00024599012451715
23361891	30781	jpa integer conversion to string for mysql query	select ...   from ...  where e.fgpvndrnumber like '%123%' 	0.729057916906021
23367864	32310	how do i write an sql function that takes an unknown amount of numbers as parameters?	select *  from tbl_list_item  where tbl_list_item.class in (   select regexp_substr(input_lst,'[^,]+', 1, level) from dual   connect by regexp_substr(input_lst, '[^,]+', 1, level) is not null ); 	0.603345474176297
23369099	15453	can you do a select * from case when statement	select saledate from tbl1 where getdate() <= '01-apr-2014' union all select saledate from tbl2 where getdate() > '01-apr-2014' 	0.623634696546304
23370632	40728	how to get the sum under different conditions in one query?	select sum(case               when active_flag = 1 then value + sal               else 0             end) as sump,        sum(case               when active_flag = 2 then value + sal               else 0             end) as sumn  from   loans  where  active_flag in ( 1, 2 ) 	8.99840645971192e-05
23370806	40603	how i can add null data to a result set, where it doesn't exist in the db - without inserting new data	select  d.device,  s.service,  r.hits from dt_devs d inner join dt_serv s on d.serviceid = s.serviceid left join results r on d.deviceid = r.deviceid 	0.00228515593871978
23381453	40345	how to get time since record submitted to db?	select timediff('2014-04-03 12:00:00','2014-04-03 11:15:00'); 	0.000161815195430663
23390409	28140	using union with three queries	select id, class_date, class_id,   sum(booked_count) as booked_count,   sum(reserve_count) as reserve_count,   sum(cancel_count) as cancel_count from (select id, class_date, class_id,   1 as booked_count,   0 as reserve_count,   0 as cancel_count  from bookings where booking_status = '#booked#' union all select id, class_date, class_id,   0 as booked_count,   1 as reserve_count,   0 as cancel_count  from bookings where booking_status = '#reserve#' union all select id, class_date, class_id,   0 as booked_count,   0 as reserve_count,   1 as cancel_count   from bookings where booking_status = '#cancelled#') as t group by class_date, class_id 	0.60470409844853
23399410	18796	asp.net sql order by certain value	select *, case requeststatus    when 'pending' then 0    when 'approved' then 1    when 'rejected' then 2    end  as requeststatusorder from leaverequests where email = @0 order by requeststatusorder 	0.0106450402059772
23407303	32599	query for retrieving columns with null value	select case        when col01 is null        then 'col1'        when col02 is null        then 'col2'        when col03 is null        then 'col3'        when col04 is null        then 'col4'        when col05 is null        then 'col5'        else null        end        which_col from   tablex 	0.0031507884302759
23408451	8617	how to get a list of all tables from the database together with column names	select table_name, column_name, data_type, is_nullable, column_default   from information_schema.columns   where table_name = 'tbl_name'   [and table_schema = 'db_name']   [and column_name like 'wild'] 	0
23412606	32669	mysql table join on itself	select  f1.file as file,  f1.status as statusin,  f2.status as statusout  from  ( select t1.file, t1.status from photo as t1 where t1.status = "raw scanned" )f1 left join ( select t2.file, t2.status from photo as t2 where t2.status = "processed" )f2 on f1.file = f2.file; 	0.122244321427091
23430421	14770	how to replace characters before a number in sql	select replace(name, substr(name, 1, regexp_instr( name, '[0-9]', 1)-1), 'port ')  from port 	0.0140798747300573
23430881	22413	i want to partition my table by the last name?	select      c.*,     counts_lastname.cnt_lastname as " from customer c inner join (   select    lastname,   count(*) as cnt_lastname   from customer   group by lastname ) counts_lastname on c.lastname = counts_lastname.lastname; 	0.00246789393388456
23451239	5135	sum if values oracle sql	select charge_type, name, sum(amount) from ( select      case          when i.charge_type = '**gsmusagecharge**' then 'gsmusagecharge'         else i.charge_type     end charge_type,     case          when i.charge_type='**gsmusagecharge**' and cp.name='service charges' then 'call charges'         else cp.name     end name,     i.amount amount  from charge.gp_schedule gp, charge.gsm_charge_plan i, charge cp  where i.code = gp.sales_audit_code  and cp.code = gp.code ) modified_names group by charge_type, name; 	0.0732080636466517
23452085	22790	get balance in sqlite3	select id,        name,        (select total(value)         from debit         where user_from = user.id           and user_to   = 1) -        (select total(value)         from debit         where user_to   = user.id           and user_from = 1) as amount from user where amount <> 0; id          name        amount     2           marie       19.77      3           peter       -2.45 	0.0764519692847511
23461042	29234	selecting the last record and comparing a datetime	select t.id as topic_id, t.name as topic_name from topics t where not exists(   select tuv.topic_id, max(tuv.created_at) as last_view, max(tp.created_at) as last_post   from topic_user_views tuv   inner join topic_posts as tp   on tuv.topic_id=tp.topic_id and tuv.created_at > tp.created_at   group by topic_id   having t.id=topic_id) order by id desc 	0
23490031	2776	converting datetime to month-year only - t-sql	select replace(right(convert(varchar, getdate(), 106), 8), ' ', '-') 	0.0405693444458236
23498737	30257	mysql date in where clause	select * from mytable where month(`date`) <> 12   or day(`date`) not between 3 and 24 ; 	0.544906940107268
23500514	16293	select transitive relation on one table	select  a.subject as element1,  a.predicate as predicate2,  a.object as pivot,  b.predicate as predicate2,  b.subject as element2 from table a join table b on a.object = b.subject; 	0.00502478928245303
23505583	30451	sql server - join 2 tables based on earliest date in 2nd table	select c.id       ,c.customer       ,c.product       ,c.reporteddate       ,datediff(hour, c.reporteddate, a.datecreated) as [timepassed]       ,a.createdby from [case] c inner join              (select *,                   row_number() over (partition by caseid order by datecreated asc) as rn             from [activity]) a  on c.id = a.caseid where a.rn = 1 	0
23509007	24552	sql month year datatypes	select month from(     select distinct(cast(datepart(year,date) as varchar(10)) + ' ' + datename(month,date)) month         ,year(date) yr, month(date) mn     from p98.dbo.recordsdaily     where date >= '2013/12/1' )x order by yr, mn 	0.00647394530976465
23510967	39335	ora-01427: single-row subquery returns more than one row error	select      account_number,      name,     (select sum(amount) from acounts b where b.[account number]=a.account_number) total from users a order by account_number 	0.691961958722857
23515356	24893	select from a table based on another table number of records oracle	select *  from table1 t1 where exists(select * from table2 t2 where closureflag = 'n' and t1.id = t2.id); 	0
23518826	33354	is it possible to group by a few different date periods in mysql?	select '1_day' as period , count(*) as total from likes where like_date>(sysdate-1) union select '7_days'  , count(*) from likes where like_date>(sysdate-7) union select '1_month'  , count(*) from likes where like_date>(sysdate-30) union select '1 year'  , count(*) from likes where like_date>(sysdate-365) 	0.00457590544659615
23519408	12122	select all for the last projetid entered	select  * from projetstaches      where projectid= (select max(projectid) from projetstaches) 	4.76294811505e-05
23526277	41040	selecting the max value from a subquery of three tables	select   section,   last_mds_mon,   days_between from   (   select     section,     last_mds_mon,     days_between,     rank() over (partition by section order by last_mds_mon desc) as rank   from     (     select state_code||shrp_id as section,max(survey_date) as last_mds_mon,((add_months(current_date,18))-to_date(max(survey_date))) as days_between     from mon_dis_ac_rev     group by state_code,shrp_id     union all     select state_code||shrp_id as section,max(survey_date) as last_mds_mon,((add_months(current_date,18))-to_date(max(survey_date))) as days_between     from mon_dis_jpcc_rev     group by state_code,shrp_id     union all     select state_code||shrp_id as section,max(survey_date) as last_mds_mon,((add_months(current_date,18))-to_date(max(survey_date))) as days_between     from mon_dis_crcp_rev     group by state_code,shrp_id     )   ) where   rank = 1 	0
23549013	26143	working with stored dates and sysdates in sql	select * from inventory where inv_input_dt < sysdate - 30 	0.780430227755132
23557568	22701	using group by with condition in oracle	select max(start_time),id    from workitem where ( name = 'map' or name = 'validate')    group by id,name   union all   select start_time,id    from workitem    where name <> 'map'; 	0.711457724394416
23567111	21512	mysql datetime difference in days, hours and minutes	select      @diff:=abs( unix_timestamp("2014-05-09 21:24:25") - unix_timestamp() ) ,      cast(@days := if(@diff/86400 >= 1, floor(@diff / 86400 ),0) as signed) as days,      cast(@hours := if(@diff/3600 >= 1, floor((@diff:=@diff-@days*86400) / 3600),0) as signed) as hours,      cast(@minutes := if(@diff/60 >= 1, floor((@diff:=@diff-@hours*3600) / 60),0) as signed) as minutes,      cast(@diff-@minutes*60 as signed) as seconds; 	0
23581451	34215	mysql - using results from one query in another query	select    a.phrase,    b.phrase from    phraseconnections pc inner join    phraseenglish as a on    pc.ideng = a.id inner join    phrasedutch as b on    pc.iddutch = b.id where    pc.cat = 3; 	0.00451072982245148
23600615	19263	how to select everything from first table where is based on third table	select      mp.modelo     ,mp.quantidade from modelosemuso me     inner join modelopeca mp         on me.modelopeca_idpeca = mp.idpeca where me.carros_idcarros = @user_param 	0
23605970	5169	check if a list of items already exists in a sql database	select groupid  from (   select groupid        , count(*) as groupmembercount        , sum(case when myuseridlist.userid is null then 0 else 1 end) as  groupmembercountinmylist   from groupuser       left outer join myuseridlist on groupuser.userid=myuseridlist.userid  group by groupid  ) as mysubquery  where groupmembercount=groupmembercountinmylist 	5.2544657036755e-05
23607095	31266	sql: select a when in a and not b or select b when in a and b	select      case when b.ipurchaseorderlineid is not null then 'b' else 'a' end as [source],     a.ipurchaseorderlineid,     isnull(b.sproductdescription, a.sproductdescription) as [sproductdescription] from purchaseorderline as a     left join goodsin as b on a.ipurchaseorderlineid = b.ipurchaseorderlineid                            and b.ddatedelivered = getdate() where b.ipurchaseorderlineid is not null        or a.drequireddate = convert(date, getdate()) 	0.0169867120755672
23618325	35082	selecting related ids from database	select receive from messages where transmit = 1 union select transmit from messages where receive = 1 	0
23619561	15667	sql find values where a term is present but not in parenthesis	select * from table where column not like '%(bob)%' and column like '%bob%' 	0.483153980225989
23633404	27381	multiple records in subquery error	select a.[job title], a.[count of id], b.[count of id] from ctrjob a inner join      ctrjob b on a.[job title] = b.[job title] where a.date = #4/2/2014# and       b.date = #5/13/2014# 	0.630311432139865
23641207	3488	count clicked links, total and unique in sql	select count(distinct user_id) as uniq, sum(count) as total from my_table; 	0.000373097069280797
23659279	9234	oracle moving average without current row	select    crd_nb,    flng_month,    curr_0380,   avg(curr_0380) over (     partition by crd_nb      order by flng_month      rows between 30 preceding and 1 preceding   ) mavg from us_ordered 	4.77723102717814e-05
23663492	9180	sql query to find most popular instances of data	select descr254, count(*) as count from sysadm.ps_is_stats_urls group by descr254 order by count(*) 	0
23668656	13168	how to get month-to-date excluding today (month to yesterday?)	select coalesce(sum(subtotal),0) from dbo.dr_trans where transdate >= cast(getdate() - day(getdate()) + 1 as date) and       transdate < cast(getdate() as date); 	0
23669212	83	displaying primary key from database in order from least to greatest in c#	select personalinfo.[id] from personalinfo order by cast(id as int) 	5.44626317495104e-05
23674196	33534	sql query second sum column squaring results	select t1.[account no], t1.[iv total], t2.[gl total] from (     select a.actnumst as [account no], sum(b.extdcost) as [iv total]     from gl00105 a     inner join see30303 b on a.actindx = b.ivivindx     group by a.actnumst ) t1 inner join (     select a.actnumst as [account no], sum(c.perdblnc) as [gl total]     from gl00105 a     left join gl10110 c on a.actindx = c.actindx     group by a.actnumst ) t2 on t1.[account no] = t2.[account no] 	0.00869468610962576
23677148	5041	column names in each table must be unique. while copy table data from one table to another in sql server	select k.transactid, k.hbarcode into khanger2013  from khanger_tbl k inner join transaction_tbl t on t.transactid=k.transactid where t.dtime <='2013-12-30 	0
23684405	9092	mysql select item from several categories returns no results	select c.id, c.name  from cars c join       _rel_cars_categories rcc on c.id=rcc.car_id  where rcc.category_id in (33,51) and c.status >=10 group by c.name having count( distinct rcc.category_id ) = 2 	0.000155691996875146
23708154	5945	sql query, get data from multiple tables and query result	select t1.b, t1.c, ..., t3.col1 as a, t3.col4 as f, t4.col as h from t3 join t4     on t3.col1 = t4.col2 join t1     on t1.a = t3.col1; 	0.00195434030743222
23709136	22963	php & mysql: query from 2 tables	select * from jobs left join companies on jobs.company_id = companies.company_id 	0.0113029667495438
23709183	30993	mysql count rows where condition	select sum(seqid0101 = 1) as seqid0101, sum(seqid0102 = 1) as seqid0102, sum(seqid0103 = 1) as seqid0103, sum(seqid0104 = 1) as seqid0104, sum(seqid0105 = 1) as seqid0105, sum(seqid0106 = 1) as seqid0106, sum(seqid0107 = 1) as seqid0107, sum(seqid0108 = 1) as seqid0108, sum(seqid0109 = 1) as seqid0109, sum(seqid0110 = 1) as seqid0110 from  ph001_hist 	0.0514699355499322
23732381	38602	timesheet relational database design	select ts.*, po.project_role from timesheet ts left join project_organization po on    po.user_id = ts.user_id and    ts.entry_date between po.start_date and po.finish_date 	0.779725046293216
23739209	2654	how to join these tables in sql	select      c.id 'client_id', g.id 'group_id', isnull(cg.client_id) from     (client c      cross join group g)     left join client_group cg on c.id = cg.client_id and g.id = cg.group_id 	0.270983455306471
23757493	18154	how do i convert columns into rows for each status	select name, 'joined' as [action], join_dt as action_date   from sometable union all   select name, 'started' start_dttm   from sometable union all   select name, 'ended', end_dt   from sometable 	0
23761345	18136	list all or specified value - ssrs parameter	select ... from mytable where @param = col or @param = 'all'; 	0.0071831571400421
23761760	36276	matching values in two record ins mysql	select `engine4_users`.*, count(value) as `count` from `engine4_users` inner join `engine4_user_fields_values` on engine4_user_fields_values.item_id = engine4_users.user_id where (engine4_users.user_id not in (4)) and (engine4_users.user_id != 1) and (engine4_user_fields_values.value in ('1', 'mubasher ', 'munir', '2', '1993-6-29', 'lahore', '54000', '5', '10', 'video gaming', 'transporter ', 'oop', 'akcent', 'star movies', '1', '21', '2010-1-2', 'nothing', '', '2012-1-4', 'nothing', 'others', '22', 'nothing')) group by `item_id` having (count(value) > 1) order by `count` desc 	0.00133336094773026
23764552	35629	how to add totals in sql	select month(b.funded_date) as 'monthnum',     count(*) as 'total' from table as b where year(b.funded_date) = 2014 group by month(b.funded_date) 	0.0441397672220353
23766032	15821	joining specific columns from different tables, incorporating group by	select     c1.blocksize, c1.bootvolume, c1.compressed, c1.systemname, c1.label, c1.caption, c1.pagefilepresent,            [dbo].[ccs_digital_storage_converter]('b', 'gb', c1.capacity) as capacity,            [dbo].[ccs_digital_storage_converter]('b', 'gb', c1.freespace) as [free space],             [dbo].[ccs_digital_storage_converter]('b', 'gb', c1.capacity - c1.freespace) as [used space],            100 * c1.freespace / c1.capacity as [free space %],            [cle_env_short], [cle_env_cat_short] from       ccs_win32_volume c1 join       [dbo].[ccs_v_server_instance_details] c2 on c1.systemname = c2.csl_server_name where      ((@p_servername = c1.systemname) or (@p_servername = 'all')) and       c2.[cle_env_short] = @p_env        c2.[cle_env_cat_short] = @p_envcat order by c2.[cle_env_cat_short] 	4.82670428569554e-05
23783827	21300	sql, know if record exist and in which table it is	select 'tab1' from tab1 where description = 'something' union select 'tab2' from tab2 where description = 'something' union select 'tab3' from tab3 where description = 'something' 	0.0112617329073229
23792546	276	limit a query with subitems	select p.name, p.puzzle, count(*) as numtools, group_concat(t.id) as tools from puzzles p inner join      tools_for_puzzle tfp      on tfp.id_puzzle = p.id inner join      tools t      on t.id= tfp.id_tool where t.id in (21,22,23,24,25,26,27) group by p.id order by numtools desc; 	0.601811083490997
23797153	13267	sql select all from day of month	select * from table1 where extract(day from `date`) =  extract(day from now()) 	0
23805387	1601	get common data from two different table	select t1.* from t1 inner join t2      on t2.firstname = t1.firstname     and t2.lastname = t1.lastname     and t2.dateofbirth = t1.dateofbirth union all select t2.* from t2 inner join t1      on t1.firstname = t2.firstname     and t1.lastname = t2.lastname     and t1.dateofbirth = t2.dateofbirth 	0
23807193	32448	getting counts per user across tables in postgresql	select     id, name,     coalesce(orders, 0) as orders,     coalesce(comments, 0) as comments from     users u     left join     (         select userid as id, count(*) as orders         from orders         group by userid     ) o using (id)     left join     (         select userid as id, count(*) as comments         from comments         group by userid     ) c using (id) order by name 	0.000315431480638589
23808074	10370	sql - convert number to decimal	select convert(decimal(15,2),12345/100.0) 	0.0165746465240223
23808925	33084	find timestamp in dates	select * from your_table where trunc(date) != date 	0.00142409334304635
23809815	25370	finding the web page which is calling a sp	select session_id, client_net_address, hostname, program_name from      sys.dm_exec_connections c  inner join     sys.sysprocesses s on      c.session_id = s.spid where      session_id = @@spid 	0.583210180463452
23812509	28990	get peer column values from same table using codeigniter and mysql	select  t2.cat_id , t2.subcat_id, t2.name from test t1 join test t2 on t1.cat_id = t2.cat_id where t1.subcat_id = 42 and t2.subcat_id <> 42 	0
23814319	28646	mysql: select nth rows where at least one has a attribute set?	select word from ((select word, 0 as ordering        from words        where special = 1        order by rand()        limit 1       ) union all       (select word, rand() as ordering        from words        limit n       )      ) t group by word order by min(ordering) limit n; 	0
23819167	7750	how to join four tables in mysql [php]	select * from posts p     inner join rings r on p.rid = r.id     inner join users u on p.uid = u.id     left join votes v on p.pid = v.pid     where p.rid in ('$rja') and p.uid != '$uid'     and p.deleted = '0'     order by p.date_posted desc" 	0.0879136367626652
23841623	41292	types don't match between the anchor and the recursive part in column "productnames" of recursive query "cte"	select productcategoryid,          count(*) as [count],           cast(max(productname) as nvarchar(max)) as productnames,           0 as [rank]    from product    group by productcategoryid    union all    select cte.productcategoryid,          cte.[count],           cast(productnames + n' , ' + productname as nvarchar(max)),           [rank]+1    from      cte inner join product        on cte.productcategoryid = product.productcategoryid        and cte.productnames not like '%'+productname+'%'        and cte.[rank] < cte.[count] 	0.00548852030839038
23842828	35710	retrieve user messages from a table and echo them relative to date	select *  from msgs  where (recipientid = '{$_session['rider_id']}' and authorid = '{$riderid}')  or (authorid = '{$_session['rider_id']}' and recipientid = '{$riderid}') order by datesent desc 	0
23844532	21730	mysql : how i can get 3 columns from multiple tables?	select     d.profile_name,     d.ddd_content,     f.profile_role from     ddx as d     inner join         forums as f         on f.profile_forum_id = d.profile_forum_id where     (profile_role = 'admin' or profile_role = 'moderator')     and forum_id = 9; 	7.83200684968337e-05
23870131	22505	mysql combine multiple joins	select     t.tid,     t.tname,     a.aid,     a.aname,     u.uid,     u.uname from     tablet t     left join t_a ta using (tid)     left join t_u ti using (tid)     left join tablea a using (aid)     left join tableu u using (uid) union select     t.tid,     t.tname,     a.aid,     a.aname,     null,     null from     tablet t     right join t_a ta using (tid)     right join tablea a using (aid)     where t.tid is null 	0.310147436830618
23879471	31931	postgresql: how to select multiple random rows with repeating results	select * from  (select floor(random()*(select count(*) from pgbench_tellers)+1) as      row_number from generate_series(1,10) ) rwr  join  (select *, row_number() over () from pgbench_tellers) original using (row_number) ; 	0.00171307382187094
23888154	28743	get single column from multiple rows in mysql	select doctorname, aday, group_concat(concat_ws('~', availfrom, availupto) separator '#') avail_time_slots from sometable group by doctname, aday 	0
23890381	19450	sqlserver - subquery return same value instead null	select l.threadname,    l.message,    csut.startdate from notifier.log l inner join devbase.dbo.cutstatustask csut on csut.campaignid = l.campaignid  where csut.campaignid = replace(parsename(replace(l.message,'&','.'),1), 'campid=', '') and (l.type like '%recurring_start%'      or      l.type like '%recurring_end%') 	0.00820457712702112
23906699	6375	how to split a string to 4 characters sub strings then concat them by hyphen?	select serial_no, group_concat(substring(serial_no, anint, 4) order by anint separator '-') from (     select serial_no, anint     from pos     cross join     (         select (4 * (units.i + 10 * tens.i + 100 * hundreds.i)) + 1 as anint         from (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) units         cross join (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) tens         cross join (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) hundreds     ) sub1     where length(serial_no) >= anint     and length(serial_no) > 15 ) sub2 group by serial_no 	0.00442715374220298
23917760	28243	casttodouble spatialite doesn't cast negative numbers	select cast('-5.84' as real) 	0.143777008980256
23921407	8438	find in sql table values that is max on 3 columns, plus max on a single column	select q.survey_id, (select max(question_id) from tblquestion where survey_id=q.survey_id), q.chapter, q.subchapter, max(q.question_number) from    tblquestion q where   q.survey_id = @survey_id and     q.chapter = (select max(chapter)                      from tblquestion qq                      where  qq.survey_id=q.survey_id) and     q.subchapter = (select max(subchapter)                         from tblquestion qq                         where qq.survey_id=q.survey_id                         and     qq.chapter = q.chapter) group by q.survey_id, q.chapter, q.subchapter 	0
23921900	37747	sql query for excluding a key value matching record for a specific condition	select pkid, detailid, type from temp where type <> 5 group by pkid, detailid, type union select pkid, detailid, type from temp  where detailid not in ( select detailid from temp where type <> 5 group by pkid, detailid, type ) order by pkid 	0
23930907	8940	get the records as per the given orderid only	select * from tblheaderfield where headerfieldid in (5,6,2,1,3,4,7,8,9,10,11,12,13,14,15) order by charindex(cast(headerfieldid as varchar), '5,6,2,1,3,4,7,8,9,10,11,12,13,14,15') 	0
23939526	3115	mysql ranking system with multiple categories	select game_id, sum(cat1+cat2+cat3) score, count(*) votes from game_ranking group by game_id order by score desc, votes desc 	0.310109498332815
23940007	37149	find unique values that do not exist in multiple columns and tables	select user.* from user left join hd_ticket on user.id = hd_ticket.owner_id left join hd_ticket as hd_ticket2 on user.id = hd_ticket2.submitter_id left join hd_archive_ticket on user.id = hd_archive_ticket.owner_id left join hd_archive_ticket as hd_archive_ticket2 on user.id = hd_archive_ticket2.submitter_id where hd_ticket.owner_id is null and hd_ticket2.submitter_id is null and hd_archive_ticket.owner_id is null and hd_archive_ticket2.submitter_id is null 	0
23952549	22032	sql server, count multiple columns	select count(*) as [count], col1, col2 from your_table group by col1, col2 	0.0389370776367993
23961222	539	prevented person names (database)	select bp.* from bannedpersons bp where (bp.firstname is null or bp.firstname = $firstname) and       (bp.lastname is null or bp.lastname = $lastname); 	0.00578775283899289
23983429	10207	what is the faster way to retrieve a column using minimum of another column	select top 1 pod.podid  from sod   join idt     on sod.itemid = idt .itemid    and sod.soid = @sodi  join pod     on pod.productid = idt.productid    and pod.duedate is not null    and (pod.orderqty >= pod.receivedqty)       join poh on poh.poid = pod.poid    and poh.statusid <> 32 order by pod.duedate, pod.podid 	0.000261646913773122
23992618	19187	joining single record in one mysql table to two records in a second	select fixture_id, date, h.team as home_team, a.team as away_team from fixtures f inner join teams h on f.home_team_id = h.team_id inner join teams a on f.away_team_id = a.team_id 	0
24011639	5705	select the latest date from joins	select t2.tempemailid, t1.emailid from tbl1 t1 left join (select *, rank() over (partition by emailid order by tempemailid desc) as topone from tbl2) t2 on t1.emailid = t2.emailid and topone = 1 	0.000510147933734586
24019940	29408	making a sql statement with multiple grouping	select year, week, location, sum(amount) as 'total amount' from [system_order]  group by location, week, year 	0.714160225988116
24022801	3482	mysql subtracting successive rows in same column	select a.id, a.length, b.length, b.length - a.length as difference from mytable a, mytable b where a.id=b.id and b.length = (select min(length) from mytable where id=a.id and length > a.length) 	0.000282175729868806
24037623	12923	get the number of similar items by year for each item	select p.name      , p.year      , p.category      , ((p.price - avg_price)/avg_price)*100 price_difference      , ttl   from product p   join       ( select category             , avg(price) avg_price          from product         group             by category      ) t     on t.category = p.category   join       ( select category,year, count(*) ttl from product group by category,year ) n     on n.year = p.year     and n.category = p.category; 	0
24043232	24594	how to join two mysql querys from two tables	select a.nome as gallery  ,count(b.titulo)  as photos  from canais a inner join galerias b on a.htd    = b.categoria  group by a.nome 	0.00173312918404851
24058185	35189	excluding from query all rows related with a value in a subquery result	select c.rec_name from composition c group by c.rec_name having sum(ing_name not in (**subquery**)) = 0; 	0
24069872	1025	mysql match value, find similar and sort, then order the sorted groups by orginal match value	select p2.name, p2.age  from people p1 join people p2 on substring(p1.name,1,1) = substring(p2.name,1,1) where p1.age < 40 and other p1 criteria order by p1.age, p2.name 	0
24070978	19537	how do i return a value of an entity in a table that is less than but closest to the value in another table for each element in the last table in sql?	select jc.classfile,        (select top 1 ml.module         from modulelist as ml         where ml.[order] < jc.[order]        ) from javaclassfilelist as jc; 	0
24077155	11041	group_concat(mysql) in sql server 2008	select     id,     (         select             date + ',' + name + ',' + comment as 'text()'         from             [table] as xml         where             xml.id = [table].id         for             xml path('')     ) from     [table] group by     id 	0.739607808182405
24103722	20098	how to put if else statement in sql where condition?	select *  from article where (year*10000+month*100+day) between (syear*10000+smonth*100+sday) and (eyear*10000+emonth*100+eday) 	0.689139272196263
24129025	36448	in microsoft sql server 2008, how can i generate specific xml tags?	select     externalstudentid1 as '@externalstudentid1',     externalsiteid as '@externalsiteid',     ...     '' as 'text()'  from     sbl.[student] for     xml path('student') 	0.156301763880108
24129423	16793	in mysql select query reuse one of the selected column	select subquery.bigquery, subquery.bigquery*100 as percent from  (   select `bigformula` as bigquery   from mytable ) subquery 	0.000346370996103845
24131783	2338	collating data in sql server	select sum(col1) , sum(col2)..... from tbl group by st 	0.297111873870246
24140021	38564	selecting unique rows with maximum values (with conditions)	select x.*   from things x   join       ( select brand             , model             , max(effective_from) max_effective_from           from things          where effective_from <= unix_timestamp()          group             by brand             , model      ) y      on y.brand = x.brand     and y.model = x.model     and y.max_effective_from = x.effective_from; + | id   | brand | model | effective_from | price | + |    1 | a     | red   |     1402351200 |   100 | |    2 | b     | red   |     1402351200 |   110 | |    3 | a     | green |     1402391200 |   120 | |    7 | b     | green |     1402358200 |   135 | + select unix_timestamp(); + | unix_timestamp() | + |       1402404432 | + 	0
24141460	20695	mysql select from table a where condition x and subselect	select count(*) as total from table_a as a where a.created >= '0000-00-00 00:00:00' and a.created <= (select table_b.`end` from table_b where table_b.`id`=13) 	0.0107314204207716
24149329	28390	how to find max value of column with null being included and considered the max	select [id]      , case when max(case when [date] is null then 1 else 0 end) = 0 then max([date]) end from yourtable group by [id] 	0.000202615223272995
24154112	15676	mysql select ... where decimal is whole number	select * from table where field = floor(field); 	0.0287640446769258
24157845	15167	sql running total from a count	select t1.hour, count(*) totalperhour, (   select count(*)    from table1 t2   where t2.year <= t1.year and t2.month <= t1.month and t2.day <= t1.day and t2.hour <= t1.hour ) totalcumulative from table1 t1 group by t1.year, t1.month, t1.day, t1.hour 	0.0022991096853315
24170333	9654	mysql query to match multiple values from two tables	select        tab_b.id from          tableb tab_b   where         tab_b.value in (select      tablea.value                               from        tablea                               where       tablea.id = 3) group by      tab_b.id having        count(distinct tab_b.value) = (select      count(tablea.value)                                              from        tablea                                              where       tablea.id = 3) 	0.000221606188885435
24192619	18826	xquery to select related node	select request.query(' from requestlog where request.exist(' 	0.0393074192281498
24199265	29303	how i can natural sort in mysql? i have followed table:	select name,  convert(replace(name, substring_index(name, reverse(convert(reverse(name), signed)), 1), ''),signed) as t, substring_index(name, reverse(convert(reverse(name), signed)), 1) as d from sortnum order by d, t asc; 	0.126665144507871
24200192	29847	sqlite3 - using record of another table in glob	select * from tablea where columna glob (select globpatterncolumn                     from tableb                     where rowid = 3) || 'some text' 	0.000737579856049447
24204144	39025	how to combine distinct and count the aggregated values	select capture_group_id, subject_id, round_id, gender, birth_year, birth_country, cnt from (select sc.capture_group_id, p.subject_id, sc.round_id, p.gender,              p.birth_year, p.birth_country,              row_number() over (partition by study_case.capture_group_id, p.subject_id                                 order by sc.capture_group_id, p.subject_id, sc.round_id                                ) as seqnum,              count(*) over (partition by sc.capture_group_id, p.subject_id) as cnt       from study_case sc join            proband p            on sc.proband_id = p.proband_id      ) t where seqnum = 1 order by capture_group_id, subject_id, round_id 	0.000423579848585983
24210937	38281	mysql select parents and child all from on table	select page.* , if( (select p.parent_id from pages p where p.id = page.id) = 0, "parent", "child" ) as page_type  from pages as page 	0
24241640	2644	mysql how to get rows with max date when grouping?	select  a.* from    tablename a         inner join          (             select  product, max(date) mxdate             from    tablename             group   by product         ) b on a.product = b.product                 and a.date = b.mxdate 	0.000578835330611292
24267845	34266	sql query to retrive data as column1 associated with column 2	select  t.id, t.version, t.[desc], t.[update date] from    table t join (     select      id, max(version) curversion     from        table     group by    id ) x on x.id = t.id and x.curversion = t.version order by t.id 	0.000488557338892615
24270762	32527	need to select most recent record, group by customer and item code	select     *      from     rdr1     inner join     (select itemcode, max(docdate) as docdate     from rdr1      where customercode= 'test001'      group by itemcode) md     on md.docdate = rdr1.docdate and md.itemcode = rdr1.itemcode 	0
24276534	2899	sql - select column multiple times	select     s.workstationname,     s.os,     s.manufacturer,     sr.softwareversion as "reader",     sf.softwareversion as "flash"   from     systeminfo s left join     softwareinfo sor on (sor.workstationid = s.workstationid) left join     softwarelist sr on (sr.softwareid = sor.softwareid and sr.softwarename = 'reader') left join     softwareinfo sof on (sof.workstationid = s.workstationid) left join     softwarelist sf on (sf.softwareid = sof.softwareid and sf.softwarename = 'flash') 	0.0105979934251916
24292271	39154	echo data from two different tables in database: echo data 2nd table not working	select * from `images` where `image-title` = '$title' 	0
24305015	30605	mysql get difference from the result of 2 fields queried	select count(`betid`),        format(sum(`betamount`),0),        format(sum(`payout`),0),        format(round(sum(`betamount`),0) - round(sum(`payout`),0),0) diff,        round((sum(`betamount`) / count(`betid`)),2),        round((((sum(`betamount`) + sum(`payout`)) / sum(`payout`)) * 100),2) from `betdb` 	0
24314308	22055	mysql join of two select result	select *  from (select id, id_cat, modello            from tbarticoli            where id_cat=5) as tba left join (select idmodello,            floor(avg(voto)) as votomedio            from tbcommenti            group by idmodello) as tbc on tba.id = tbc.idmodello 	0.0247978894457848
24324734	40883	get month columns from datetime column and count entries	select name,        sum(case when month(datea) = 01 and timeworked is null then 1 else 0 end) as jan,        sum(case when month(datea) = 02 and timeworked is null then 1 else 0 end) as feb,        ...        sum(case when month(detea) = 12 and timeworked is null then 1 else 0 end) as dec,        sum(case when timeworked is null then 1 else 0 end) as sum from table t where year(datea) = 2013 group by name 	0
24335249	10890	tracking differences between two sql tables (added, removed, changed)	select code-id, 'added' result from a except select code-id, 'added' result from b union all select code-id, 'removed' result from b except select code-id, 'removed' result from a union all select code-id, 'changed' result  from a join b on a.code-id = b.code-id  where a.code-name-1 != b.code-name-1 or a.code-name-2 != b.code-name-2 	0.00100853999801263
24346420	3103	how to deal with subquery which returns more than one value	select top 1 id from table1 order by col1 desc, col2 asc 	0.0124097384235829
24351335	24538	ms access select .. into statement disordered	select * from something 	0.649428750538895
24375032	27579	count function and inner join on multiple tables	select count(file_id) as 'pending files', projects.project_id, projects.project_name, projects.status, projects.start_date from ((project_manager  left join files  on project_manager.mag_id = files.manager_id and project_manager.mag_id = 11 and file_status = 'pending' and project_manager.project_id = files.project_id ) inner join projects on projects.project_id = project_manager.project_id) where project_manager.mag_id = 11 group by projects.project_id, projects.project_name, projects.status, projects.start_date order by projects.status, projects.start_date desc 	0.631155511879601
24381510	3008	sql parents and children (child cant have children)	select  case when parent_id is null then name else concat(' from    humans order by         case when parent_id is null then human_id else parent_id end,         case when parent_id is null then 1 else 2 end 	0.000507594015939955
24381747	26109	sql replace value in 1 row	select [hostname],[assettag],[business],[building],     case [building]              when 700 then 'ict'             when 879 then 'sales'             else 'value if not 700 or 879'     end as building from [osddb].[dbo].[all_machines] 	0.00858162464251814
24398431	30532	sql average from multiple columns	select (125hz+250hz+500hz+750hz+1000hz+1500hz+2000hz+3000hz+4000hz+6000hz+8000hz)/11 as avehz from table_name 	0.000304528827921756
24399393	6528	how to retrieve 2nd latest date from a table	select col1, col2, max(col3)  from test  where col3 < (select max(col3)                from tab1) group by col1, col2; 	0
24400438	33346	how to hide an alias column in mysql edited	select wp_id from (select cl.wp_id,( 3959 * acos( cos( radians(12.91841) ) * cos( radians( y(gproperty) ) ) *               cos( radians( x(gproperty)) - radians(77.58631) ) + sin( radians(12.91841) ) *               sin( radians(y(gproperty) ) ) ) ) as distance       from db1.geofeature gf join            db2.c_loc cl             on gf.o_type = 256 and cl.c_info_id = 146 and gf.o_id = cl.wp_id     ) t where distance < 10 order by distance limit 10; 	0.279719960398294
24409516	2483	mysql count week total of current month	select yearweek(`date`),         @n := @n + 1 as week_number,        count(id) as week_total from edp_orders  cross join (select @num := 0) n where year(`date`) = year(curdate())  and  month(`date`) = month(curdate())  group by yearweek(`date`) 	0
24430907	19558	look for count when selecting a variable	select count(case when xpr.frevaluationprice <> d.fupplupenranta then 1 else null end) select count(case when xpr.frevaluationprice <> d.fupplupenranta then null else 1 end) from... 	0.0832988143980794
24430992	16201	query based on the difference in number of occurrences in other tables	select * from table_main where (select count(*)        from table_additions        where entry_id = table_main.entry_id       ) >       (select count(*)        from table_deletions        where entry_id = table_main.entry_id       ) 	0
24432908	37790	assign a row a number from 1 to x then loop - in sql	select     id,    (row_number() over(order by id) - 1) % 4 + 1 as nr  from     tbl 	0
24438838	999	get longest matching number (sql)	select min(pattern), score from table t group by score; 	0.000262053682872239
24441993	39534	sql -- are there are any rows where a column value is greater than 6?	select * from `at_lesson_assignments`  aa  inner join `at_lesson_assignments_visibility` at on aa.assignment_id = at.assignment_id where unit > 6 	0
24453277	8629	one-to-one relation through pivot table	select s.name, t.team_name      from team t                   join stadium s                  on (t.stadium_id = s.id)  	0.528185278979512
24460151	29487	postgres synonym and prefix results together	select      *,      ts_rank_cd(to_tsvector('location', name), to_tsquery('location_nosyn', 'lac:*'),16) as ftsrank from profile_name  where iso_code='en-ca'    and to_tsvector('location', name) @@ to_tsquery('location_nosyn', 'lac:*')    and ts_rank_cd(to_tsvector('location', name), to_tsquery('location_nosyn', 'lac:*'),16) >= 0 order by ftsrank desc 	0.330329214863061
24463426	9462	how can i show a count value in sql instead of listing out many rows?	select name exam, coalesce(count(objectiveid), 0) objectives, coalesce(count(testid), 0) tests from exam left join test on test.examid = exam.examid left join objective on objective.examid = exam.examid group by name; 	0
24464466	7334	how to make inner join two times to single table in sql server	select tour_details.id, tour_details.tour_name, tour_details.from_city, tour_details.to_city, tour_details.cost,  tour_details.details,tour_details.duration, b.name as fromcityname, a.name as tocityname  from tour_details  inner join city_master b on b.id  = tour_details.from_city inner join city_master a on a.id = tour_details.to_city  order by tour_details.id desc 	0.0188662043557605
24467025	26175	database: how to create the update cascade tables and query data?	select workreport.*  from workreport, employee  where employee.sno = workreport.sno  and employee.btitle = "employee" 	0.028432759196741
24488429	32391	sql server count some rows and leave the rest	select  rowno, componentref,         case when componentref is null then 'userscount' + ucsum else componentref end from    (         select  *,                 sum(case when componentref is null then cast(replace(componenttitle, 'userscount', '') as int) end) as ucsum,                 row_number() over (partition by componentref order by rownum) rn         ) q where   componentref is not null or rn = 1 	0.00148674942441285
24494637	4439	sql - group by id and transform rows to columns	select  id,          min(case when cat = 'small' then 'small' end) small,         min(case when cat = 'medium' then 'medium' end) medium,         min(case when cat = 'large' then 'large' end) large from yourtable group by id 	0.000371732680570718
24518077	34397	how to filter records in where condition based on a sql case statement	select count(1) from (  select case                   when [cash-amt] > 0 then '1'                   when [prod-n] = '42'                        and [tran-code] in ( '-1', '-2', '-3' ) then '17'                   when [gli-src] = '8' then '7'                   when [prod-n] = '42'                        and [gli-src] = 'l'                        and [tran-code] in ( '1', '2', '3' ) then '7'                   when [gli-src] = 'l'                        and [prod-n] = '60'                        and [tran-code] in ( '4', '5', '6' ) then '7'                   else '4'                 end as tran_code,                 [cash-amt],                [gli-src]         from   txn) as t where [cash-amt] <= 0  and [gli-src] = '8' and tran_code = 7 	0.0144905323673952
24521352	10654	sql max of a sum (two rows with same value)	select i.item from inventory i inner join prices p on p.item = i.item group by i.item having sum(price) = (select max(sum_price) from (select sum(price) over (partition by item) sum_price from prices) a); 	0
24524099	20330	how to display columns as rows in sql server	select pm members from tbl union all select spm from tbl union all select qa from tbl 	0.000253620515473124
24535836	14595	group by month where range of dates	select      to_char(earliest_monthly_date, 'yyyy-mm') march,      count(netid) unique_login_count from      report_service_usage  where      earliest_monthly_date >= to_date('2014-03-01', 'yyyy-mm-dd') and earliest_monthly_date <= to_date('2014-03-31', 'yyyy-mm-dd') group by      to_char(earliest_monthly_date, 'yyyy-mm') order by      to_char(earliest_monthly_date, 'yyyy-mm') asc 	9.39766778923835e-05
24537254	18715	create oracle xml view	select    m.id as metadata_id, x.* from   metadata m,   xmltable('/metadata/states/state'        passing xmltype(m.xml_string)        columns status_id integer path '@status',                status_label varchar(32) path '@label') x; 	0.464339157127986
24548916	39283	sqlite: getting difference from two different column values	select igs.invoiceid, (val1 - val2)   from (select invoiceid, sum(price) as val1           from invoicegarmentservice          group by invoiceid) igs   join (select invoiceid, sum(amount) as val2           from payment          group by invoiceid) p     on (igs.invoiceid = p.invoiceid)  where igs.invoiceid = '1001' 	0
24548961	6645	finding most instances of a month	select * from (   select to_char(dateregistered,'mm') as month, count(*) as cnt   from pet   group by to_char(dateregistered,'mm')   order by count(*) desc ) where rownum = 1; 	0
24578321	14517	mysql: select last row of each pair	select c.* from chat c join (select     max(id) max_id,     (case when user < friend then user else friend end) user_a,     (case when user < friend then friend else user end) user_b from chat     group by user_a, user_b) t1 on t1.max_id = c.id 	0
24611278	27551	sql select rows with max date	select * from `message` `t`  where `to_user_id`='1' and  `date` =     (select max(`date`) from `message` `t2`      where `t2`.`from_user_id`=`t`.`from_user_id`     and `t2`.`request_id`=`t`.`request_id`    ); 	0.00643483860047149
24619140	41198	adding 90 days to created date	select     dateadd(qq, datediff(qq, 0, max(time_stamp)) + 1, 0) as startdate,     dateadd(qq, datediff(qq, 0, max(time_stamp)) + 2, 0) as enddate from survey where mainhospital = 'hospital1' 	0.00266499869335226
24624063	19441	mysql - modify query depending on field value	select * from specimen,      topography_index,      morphology,      function where substring(specimen.topography_index, 2, 2) = topography_index.topography_index_code   and specimen.topography_index = '_organ_'   and if(specimen.snop_axis = 'm', morphology.morphology_code = specimen.snop_code, functions.function_code = specimen.snop_code); 	0.00132145237632973
24633541	29667	single request search in multiples tables using join table	select teledis.nameid from teledis  where vulcain like '%xxx%' union select teledis.nameid from joinafr     join teledis         on joinafr.teledis_id = teledis.idteledis     join afr          on joinafr.afr_id = afr.idafr where afr.name like '%xxx%' union select teledis.nameid from softs     join software_cache         on softs.id_soft_cache = software_cache.id     join joinsoft         on softs.idsofts = joinsoft.soft_id     join teledis         on joinsoft.soft_id = teledis.idteledis where software_cache.name like '%xxx'; 	0.030800781479623
24641609	11058	what is simplest query to display unique values in each column with their count?	select      rec_ins_dt , count(*) over (partition by rec_ins_dt) as rec_ins_dt_count,     rec_updt_dt , count(*) over (partition by rec_updt_dt) as rec_ins_dt_count from <your-table>; 	0
24652962	7566	add list of tables and columns from database to database	select dbms_metadata.get_ddl ( 'table', table_name ) from user_tables; 	0
24654234	40634	how to combining query's with missing results?	select id, name, operator, time1, time2, time3 from basetable q left join timetable1 on <join condition1> left join timetable2 on <join condition2> left join timetable3 on <join condition3> 	0.251070545898131
24661290	28890	creating an ssrs table with data from two different database tables	select a.customerid, count(1) as transactioncount from tablea a inner join tableb b on a.customerid = b.customerid group by a.customerid 	0.000239411430025843
24661442	21651	sql query with sum of sum	select coalesce(totalowed,0) - coalesce(totalpaid,0) from (  select  custid,                  sum(owe) totalowed         from table1          group by custid) t1 full join ( select  custid,                     sum(paid) totalpaid             from table2             group by custid) t2     on t1.custid = t2.custid where coalesce(t1.custid,t2.custid) = 112 	0.131379828909243
24668292	5101	two column name same using join in mysql	select comp.name,production_amount from production  as cust inner join location as comp on cust.location_id = comp.location_id  inner join crops as crop on cust.crop_id=crop.crop_id  where cust.year_of_production =2004 and crop.name="paddy" 	0.00307111132995793
24668531	31141	sql query to find relevant result	select colname  from tablename  where colname like '%test%' order by case when colname like 'test%' then 1 else 2 end, colname 	0.0302540460866747
24672827	13669	how to find the closest date postgresql	select userid,        state,        ctime as start_time,         lead(ctime) over (partition by userid order by ctime) as end_time from userstate; 	0.0011811440727669
24679911	2460	select and delete entries from database in one go	select * from sometable      where foo = bar      and  your_primary_key > last_checked_value      order by your_primary_key  limit 100;  delete from sometable      where  your_primary_key      in (value1,value2,...,...,value100); 	4.58038211657823e-05
24685577	9637	get records of two separate columns in one column mysql	select      sale_date as all_dates from sales union all select      purchase_date as all_dates from purchase 	0
24697352	26979	mapping specific columns of the first n results of one table to columns of another table	select ut.userid,        max(case when seqnum = 1 then ut.tagid end) as populartag1id,        max(case when seqnum = 2 then ut.tagid end) as populartag2id,        max(case when seqnum = 3 then ut.tagid end) as populartag3id from (select *, row_number() over (partition by userid order by count desc) as seqnum       from v_user_tag_counts      ) ut group by ut.userid; 	0
24700197	1553	sql create query based on data from multiple tables	select s.id, u.nickname1 as userid, c.nickname1 as clientid, t.nickname1 as timeid from slips s left join username u on u.id = s.userid left join clientnames c on c.id = s.clientid left join timeactnames t on t.id = s.timeid 	0.000235236544335877
24703884	1862	sql server - how to combine query and subquery results in a single node in a for xml path t-sql query	select (     select       [customer]      ,( select           [id] as [@id],           [item] as [data()]         from @orderdetail od         where od.fk_order = ot.id         for xml path('d'),type       )     from @ordertbl ot     for xml path('c'),type   ) for xml path('b'), root('a') 	0.236234724763231
24712761	31964	comparing two paramters in a sql server function	select @countb = count() from product where filteredviewname='filteredciti_ac' and attributename ='c_products' and value in (select * from crm_fn_ac(@attributevalue)) 	0.223230824969205
24718737	30776	finding the difference (subtraction) in sql	select       sum(case when orderdate >= '2013-01-01' and orderdate < '2014-01-01' then qty end) yr2013     , sum(case when orderdate >= '2014-01-01' and orderdate < '2015-01-01' then qty end) yr2014     , sum(case when orderdate >= '2014-01-01' and orderdate < '2015-01-01' then qty end)     - sum(case when orderdate >= '2013-01-01' and orderdate < '2014-01-01' then qty end) diff from customers  natural join orders natural join itemsordered natural join items where orderdate >= '2013-01-01' and orderdate < '2015-01-01' and description ='tshirt'; 	0.00997029016967135
24733196	22078	how to query an array of json in postgresql 9.3?	select * from delivery where '1' in (    select a->>'id' from json_array_elements(items) a ) 	0.109660812903447
24733230	19055	mysql query two different colums with same foreign table	select a.network,         a.cidr,         a.vrfold_id,         b.name as vrfold_name,         c.name as vrfold_backbone_name,         a.vrfnew_id,         d.name as vrfnew_name,         e.name as vrfnew_backbone_name from networks a join vrfs b on a.vrfold_id = b.id join backbones c on b.backbones_id = c.id join vrfs d on a.vrfnew_id = d.id join backbones e on d.backbones_id = e.id 	0
24736971	37264	mysql - get all posts (distinct) with tags	select post_id,         group_concat(tag_id) as tag_ids from category_post_tag  where category_id = 1 group by post_id 	5.11870077474105e-05
24739556	22665	assign an id value for every set of duplicates	select      dense_rank() over (order by first_name, last_name) id,       t.* from table1 t; 	0
24740251	22291	where clause in count	select count (case when [column]>20 then 1 else null end) as [a], count (case when [column]<20 and [column]>10 then 1 else null end) as [b] from table 	0.706313476576191
24759761	33728	deselect duplicates in sql	select max(id), subid from table group by subid order by subid desc 	0.268485277920079
24761888	3344	how to obtain row with a column name that exists in two tables which is not unique?	select name,uuid from vendors where uuid='11ddasa' union select name,uuid from customer where uuid='11ddasa' 	0
24774628	25044	sql group by and get combinations?	select name, cnt, count(*) from  (    select serial, name,       count(*) over (partition by serial) as cnt     from your_table  ) a group by name, cnt 	0.00680354435289731
24791226	21806	sum or subtraction upon condition in mysql query	select sum(case when ce_type = 'in' or ce_type is null then payment_amount                 when ce_type = 'out' then - payment_amount            end) as payment_amount from customer_payment_options where real_account_id = '11' and real_account_type = 'hq' and company_id = '1'; 	0.476786828600542
24791238	25942	grabbing some part of string using sql server 2012	select replace([column-2],'- x','- zz x') from yourtable 	0.11608990298846
24799202	25454	how to fetch average rows per day?	select count(*)/count(distinct `created`) from `mytable`; 	0
24802334	614	how can i extract data from a mysql database in random order?	select * from (select * from users order by rand() limit 10) tb order by id 	0.000720866184475064
24803865	5637	grouping a time field into 5 minute periods in sql server	select timefromparts(          datepart(hour, yourtimefield),          datepart(minute, yourtimefield) / 5 * 5, 0,          0,          0) from yourtable 	0.000170905407168203
24811640	26047	mysql select and in where and return two values	select * from `table1` where price between (select pricerangemin from `table2`         where pricerangeid='$pricerangeid') as min_price and (select pricerangemax from `table2`         where pricerangeid='$pricerangeid') as max_price 	0.0039310572260442
24812606	16301	sql statement to group and count duplicates	select reports.id, reports_users.name, count(reports.id) as count from reports left join reports_users on reports.user_id = reports.id group by reports.id 	0.341942498323496
24820931	28405	size of fields in bytes per table sql	select  o.name table_name, c.name colimn_name, c.max_length, t.name type from sys.columns c join sys.objects o on c.object_id=o.object_id and o.type='u' join sys.types t on c.system_type_id=t.system_type_id 	0.000427591373669249
24821410	1411	how to select all data with inner join	select a.h1, b.h2 from table_1 a left join table_2 b on a.h1 = b.h1 	0.0837123600359641
24836004	8489	sql select records with minimum number of related records	select m.*, t.*  from monkeys m  inner join monkey_hangouts h on m.id = h.monkey_id  inner join trees t on t.id = h.tree_id where m.id in (select monkey_id      from monkey_hangouts     group by monkey_id     having count(*) > 1) order by m.id 	0
24836207	30943	implementing one to one and one to many query together in sql	select a.menu_id, b.menu_id, c.menu_id, d.menu_category_id, e.menu_item_id,          f.menu_subitem_id from user_menu a join menu_details b on a.menuid = b.menuid join menu_times c on b.menuid = c.menuid join menu_categories d on c.menuid = d.menuid join menu_items e on d.menu_category_id = e.menu_category_id join menu_subitems f on e.menu_item_id = f.menu_item_id where a.menu_id = 2 	0.00629173709086499
24838186	20171	sql subquery returns more than one value	select a.* from   choices c        inner join position p on c.positionid = p.positionid        inner join adverts a  on p.name like '%' + a.name + '%' where  c.cvid = 1230 	0.0389342654671889
24873561	12670	select the oldest of the most recent lines	select scores.*  from scores inner join (   select max(date) last, name   from scores   group by name ) last_temp_table on scores.name = last_temp_table.name and scores.date = last_temp_table.last order by scores.date asc limit 1; 	0
24875194	38591	change column type for multiple tables with same column name	select 'alter table ' + quotename(schema_name(schema_id)) + '.' + quotename(t.name) + ' alter column ' + quotename(c.name) + ' nvarchar(50)' from sys.tables as t inner join sys.columns c on t.object_id = c.object_id where c.name like '%columniwantchanged%' 	0.000206407367639847
24880029	796	mysql query, get user_id then get restaurant_id then get restaurantname from 3 tables that match email at user table	select favrst_id, fr.rst_id, rst_name, rst_city,  rst_cuisine, rst_phone, rst_latitude, rst_longitude from user u inner join favouriterestaurant fr on u.user_id = fr.user_id inner join restaurant r on fr.rst_id = r.rst_id where user_email = "%$email%" 	0
24905218	8464	add rows to data of a view	select group,number,text from view union select [group],0,min(text) from view group by [group] 	0.00099436677241549
24909897	21954	change select statement value using sql	select  'com001',  'john',  case  when cast('01-jan-4501 00:00:00' as date) > cast('01-jan-2100 00:00:00' as date) then cast(getdate() as varchar(30)) else '01-jan-4501 00:00:00' end 	0.170140058434988
24927245	23963	simplifying mysql query - 2 queries into 1	select distinct t2.word from table t1  inner join table t2 on t2.entity=t1.entity where t1.word="blue"; 	0.356555378704614
24933415	14672	how to filter table according to data in postgres?	select t.tablename, c.reltuples from pg_tables t join pg_class c on c.relname = t.tablename where schemaname = 'public' and reltuples > 0; 	0.00128944319989718
24934761	36160	calling stored proc that has default value parameters	select a.default_value   from sys.dba_arguments a   where a.object_name = whatever and         a.argument_name = whatever; 	0.354933441494194
24938866	29873	how to combine all rows into one	select          a.objectid,         ltrim(rtrim(a.attr1397)) 'lastname',         ltrim(rtrim(a.attr1395)) 'firstname',         ltrim(rtrim(a.attr1400)) 'id',         temp.cars 'car name',         temp.polnumber 'pol number'     from          dbo.nstance1029 a      cross apply (         select ltrim(rtrim(b.attr1624))  + ','         from nstance1048  as b         where a.objectid  = b.fk16           for xml path(''))          temp(cars)     cross apply (         select ltrim(rtrim(b.attr1626)) + ','         from nstance1048 as b         where a.objectid =  b.fk16         for xml path(''))          temp(polnumber) 	0
24939064	30772	join two tables but only get most recent associated record	select item,sales.price from inventory i      cross apply(select top 1 price                  from sales s                  where i.id = s.inventory_id                  order by date desc) as sales 	0
24946509	5634	multiply for hours by rate	select    (substring(hours,1,2) + substring(hours,4,2)/60 + substring(hours,7,2)/3600) * rate as pay from user_hours; 	0.00225791247174953
24950646	26582	how to get the count of the subgroup in sql	select t1.function,  sum(case when color = 'green' then 1 else 0 end) as green,  sum(case when color = 'red' then 1 else 0 end) as red,  count(t1.priid) as total from table1 t1  left join table2 t2 on t1.priid = t2.priid group by t1.function 	0.000825055882735109
24978304	41238	use the result of the mysql select query as a where condition in the same query	select if(`key` < 900, `key`, null) `key` from ( (     select max(  `peg_num` ) as  `key`      from  `list`      where  `list_id` =1     ) as  `derivedtable` ) 	0.00696511757007485
24982010	29070	firebird howto count all record in table and sort max to min	select customer, count(*) as freq from table_1 group by customer order by 2 desc, 1 limit 10 	0
24982670	3306	sql query to join four tables	select u.user_id,        u.first_name,        u.last_name,        sum(case when typ = 'nda' and yesno = 1 then 1 else 0 end) as nda_signed,        sum(case when typ = 'per' and yesno = 1 then 1 else 0 end) as vw_perm   from user u   join (select investment_id, user_id, nda_signed as yesno, 'nda' as typ           from nda         union all         select investment_id, user_id, view_permission, 'per'           from permission) x     on u.user_id = x.user_id where investment_id = 'xyz' group by u.user_id,        u.first_name,        u.last_name 	0.274419729557501
24989365	9412	sorting a string numerically in sql server	select * from yourtable order by cast( substring(yourcolumn, 6,len(yourcolumn)) as int) 	0.323789043638024
24991346	21238	get horizontal wise max value	select name, greatest(m1, m2, m3, m4) as max_value from yourtable 	0.000282302981344058
24998074	29730	group a column together where meets several other column conditions	select  payrollid,  agentid,  ptid,  serviceid,  dateincured,  case when (dateincurred between '2014-05-19' and '2014-05-25') then sum(hours) end week1,  case when (dateincurred between '2014-05-26' and '2014-06-01') then sum(hours) end week2 from  your_table_name group by payrollid, agentid; 	0.00180355489156697
25008415	10299	sql convert varchar value to datetime	select cast('2014-07-28 18:05:14' as datetime) 	0.0137234373290739
25010758	34725	sql: select to add an extra **non-null** column?	select 'online' as src, title, author, genre, rating from table; 	0.0101330929131309
25017712	39286	how to select only one record for each primary key item from joined table?	select dtl.id,            dtl.city_id,            dtl.hotel_name,            dtl.country_code,            min(dsc.desc_type)   keep (dense_rank first order by case dsc.desc_type when 'general' then 1 when 'location' then 2 when 'rooms' then 3 when 'lobby' then 4 else 5 end) desc_type,            min(dsc.description) keep (dense_rank first order by case dsc.desc_type when 'general' then 1 when 'location' then 2 when 'rooms' then 3 when 'lobby' then 4 else 5 end) description       from (select htl.id,                    htl.city_id,                    htl.hotel_name,                             cty.country_code               from hotel htl                    left outer join city cty                      on (htl.city_id = cty.city_id)) dtl            left outer join dsc              on (   dtl.id = dsc.id                 and dtl.city_id = dsc.city_id)     group by dtl.id,              dtl.city_id,              dtl.hotel_name,              dtl.country_code, 	0
25027803	12932	select distinct column_a and group by column_b	select     country,     count(distinct ip) views from views group by country order by country; 	0.0991643070580027
25037981	37530	mysql - make sum of all entries and then compare it with a value	select sum(buy_price) as price from items_db where item_id in (14,74,78) having price > 100 	0
25049326	8275	sql query won't concatenate my results	select c.customer_id, c.l_name as surname,  c.f_name as 'first name', c.travel_date, t.tour_name,  group_concat(s.f_name, s.l_name ) as staff_concat from customers as c  left join tour as t on c.tour_id = t.tour_id left join staff_day as sd on c.tour_id = sd.tour_id left join staff as s on sd.staff_id = s.staff_id left join staff_day as sd_2 on sd_2.sd_date = c.travel_date  where  c.travel_date >= '2014-07-08 00:00:00'  and c.travel_date <= '2014-07-08 23:59:59' and sd.sd_date >= '2014-07-08 00:00:00'  and sd.sd_date <= '2014-07-08 23:59:59' and c.customer_id not in (select o.customer_id  from customers as c, orders as o  where c.travel_date >= '2014-07-08 00:00:00'  and c.travel_date <= '2014-07-08 23:59:59' and c.customer_id = o.customer_id ) group by c.customer_id 	0.644342641932197
25056573	13387	how to dynamically generate sql statements that converts any clob to varchar2	select ' || listagg( case t.data_type    when 'clob' then      decode('&#ignore_clob#',     'no', 'dbms_lob.substr ('||t.column_name||', 4000, 1) as '|| t.column_name,      'yes','')     else t.column_name end   , ', ') within group (order by column_id, table_name) || '  from #source_table a' query from user_tab_cols t where t.table_name = '&#source_table#'; 	0.0364055160870733
25061618	29051	use if…then sql query and return int and string	select case          when (capacity-capacityoccupied)= capacity            then 'empty'         when (capacity-capacityoccupied)=0             then 'full'         else cast((capacity-capacityoccupie) as varchar(10))    end as salable, *  from room 	0.13643203015399
25065139	18915	find entities with multiple relations	select      p.id  from photo p join photoconnect pc on pc.photo_id = p.id join photoconnect pc1 on pc1.photo_id = p.id where pc.outside_name = 'country' and pc.outside_key = 6    and pc1.outside_name = 'region' and pc1.outside_key = 13 group by photo_id 	0.0860985478713031
25065908	19662	combining multiple select into results into one variable	select cast(t1.value as varchar(20)) || ', ' || cast(t2.value as varchar(20))      into v1      from table as t1, table as t2      where t1.year <= parameteryear        and t2.yearinteger >= parameteryear; 	0.000579647340272023
25074000	3763	calculate average time difference between two datetime fields per day	select convert(date, bookeddatetime) as date, avg(datediff(minute, bookeddatetime, pickupdatetime)) as averagetime     from tablename      group by convert(date, bookeddatetime)       order by convert(date, bookeddatetime) 	0
25080708	14774	mysql query returning entire table with possible values from a second table	select ec.event_category_id, ec.event_category, if(uec.user_id is null, 0, 1)  from event_categories ec      left join users_event_categories uec         on uec.event_category_id = ec.event_category_id and uec.user_id = 1223 	0
25094865	16757	how do i join all data in 1 col of a table2 to table1 whilst keeping non matching data in table1	select   t1.col1,           t1.col2,           t1.col3,           t2.col2 as col4 from     table1 t1          left join table2 t2              on t1.col1 = t2.col1  order by t2.col2 asc 	0
25095065	40320	creating a migration for building a table whose columns are derived from rows of another table	select group_concat(distinct namecol) as namecols from tbl 	0
25103909	22160	select users where match then search a second table	select users.user, table2.total from users left join table2 on users.user = table2.total where users.user = 'marketing' or users.user = 'sales'; 	0.00017366974439154
25104226	41061	results dependent on values in other table	select   a.*,   case ax.highest   when 2 then 'error'   when 1 then 'warning'   else 'normal' end from applicationservers a outer apply (   select max(alertstatus) as highest   from alerts b   where a.servername = b.servername ) ax 	0.000955745376902355
25107888	3703	sql range join (not between)	select p.*   from ports p   left join whitelist w     on p.id between w.port_start and w.port_end  where w.port_start is null 	0.101647451545327
25121860	26089	select columns, but casting all columns of given type	select cast(col1 as int),cast(col2 as int).. from table 	0
25134006	39207	returning random rows that are evenly spread over a grouping	select top 50 q.id, q.chapter ,         row_number() over(partition by chapter order by newid()) as row from questions q order by row 	0.000736099029992339
25145304	25075	detecting last activity on table	select orders.orderid, max(posteddate) as maxdate from orders join ordernotes on orders.orderid = ordernotes.orderid where orders.customerid = 1 group by orders.orderid having max(posteddate) <= now() - interval 2 hour 	0.00400568900277019
25165879	38749	sql totals query with non-aggregate fields	select   m.id, m.datecolumn, m.note from   (select max(datecolumn) datecolumn, id    from mytable    group by id) sub inner join mytable m on m.id = sub.id and m.datecolumn= sub.datecolumn 	0.449742359744403
25174862	11915	sql group by and sum	select   continent, sum(population) from     world group by continent having   sum(population) >= 100000000 	0.23443821986608
25203236	38155	selecting a column from ms-access database which has linked tables	select distinct coursecode.coursename from student join coursecode on student.courseid = coursecode.id where student.id = ? 	0.000149860193657615
25205285	8263	sql select multiple counts in the last 12 months including missing months	select    d.d,   datename(month, d.d) as [month],    year(d.d) as [year],    isnull(priority.name,'p1'),    count(work.id) as count from d  left outer join work on completetime >= d.d and completetime < dateadd(month, 1, d.d) cross join priority on work.priorityvalue = priority.value group by d.d, isnull(priority.name,'p1') order by d.d; 	0
25233655	8328	a table of occurances of pattern in an sql table field	select t.txt_id, ta.tag_id from text t join      tags ta      on t.txt_content like concat('%<', ta.tag_name, '>%'); 	0.000369082566952136
25247547	4497	sql select pattern like column_name	select column_name from table_name  where instr('c:/tests/two/fail/results', column_name) > 0; 	0.624914928197698
25262086	19051	specified group by in mysql	select a.id,            a.b_id,            a.picture      from table_name a left join (        select b_id, min(id) min_id          from table_name         where b_id > 0      group by b_id           ) b         on a.b_id = b.b_id       and a.id = b.min_id     where a.b_id = 0        or b.b_id is not null 	0.257890353980579
25262853	22421	group by on same table and include all data like names	select name,         clientid,         sum(case when status = 2 then 1 end) as status_2,        sum(case when status = 4 then 1 end) as status_4 from your_table group by name,          clientid 	6.4723711828654e-05
25267339	37130	foreign key select only one record from table	select * from m_sales  join (select sales_id, max(country_code) as country_code                     from m_sales_country group by sales_id     ) m_sales_country on m_sales_country.sales_id = m_sales.sales_id 	0
25270955	22925	return a result even if select is empty	select p.id, p.name, p.img, p.template_usage, t.name as tpl_name from platforms as p  left join xml_template as t on t.id = p.template_usage 	0.0341953640949674
25275180	22560	iterate through values of a table variable in a stored procedure	select * from {your table} where id in (select orderrequestid from ids) 	0.0127339762443398
25277527	14406	make it appear in not-submitted list	select * from students where students.subject_class='" + session["subject_class"].tostring() + "'        and students.subject_id = '" + session["subject_id"].tostring() + "'        and not exists (select *                       from submissions                       where submissions.student_id = students.student_id                             and submissions.subject_id = students.subject_id                             and submissions.proj_sub = '" + session["proj_sub"].tostring() + "') 	0.210160821782715
25278844	16490	convert row to column and group by key	select departmentname, max(case foo_table.keyid when '4' then foo_table.score end) as [4], max(case foo_table.keyid when '5' then foo_table.score end) as [5], max(case foo_table.keyid when '6' then foo_table.score end) as [6]      from foo_table group by departmentname; 	0.00162941441320116
25288834	3844	there's any way to know the ip of a query sender?	select substring_index(host, ':', 1) as 'ip' from information_schema.processlist where id=connection_id(); 	0.0172799949458358
25289869	21223	how to get all pks after grouping them (finding duplicates)	select distinct ta_pk, tc_pk from (   select ta.pk as ta_pk,           tc.pk as tc_pk,           count(*) over (partition by ta.fk2) as cnt   from ta     join tb on ta.fk2 = tb.pk     join tc on ta.fk1 = tc.pk ) t where cnt > 1; 	0
25291161	12182	two queries, duplicate results	select      sp.room_type_id,      sp.slot_price,      sp.slot_time,      sp.slot_date,      sa.slot_avail_clean,      sa.slot_avail_noclean    from rn_slots_prices       sp join rn_slots_availability sa on   sa.hotel_id     = sp.hotel_id     and   sa.room_type_id = sp.room_type_id and   sa.slot_date    = sp.slot_date where       sp.hotel_id  =  5           and      sp.slot_date = '2014-08-12' and      sp.slot_time = '00:00:00' 	0.0112831924392922
25291422	23998	querying one of many columns based on value	select t.id, t.productid, fv.factor, fv.value, fv.pos from table t cross apply (     select pos = 1, factor = factor01, value = value01 where factor01 <> ''     union all select 2, factor02, value02 where factor02 <> ''     union all select 3, factor03, value03 where factor03 <> ''     ...     union all select 15, factor15, value15 where factor15 <> ''     ) fv 	0
25291882	8851	sql server - a query to generate a joins path from one table to another?	select a.table_name, a.column_name, b.table_name  from      information_schema.columns a       inner join      information_schema.columns b on          a.column_name = b.column_name and         a.table_name <> b.table_name  where a.table_name = 'yourstartingtable' or b.table_name = 'yourdestinationtable' 	0.000698171616118226
25297352	12773	sql query for joining one or another table	select c.id,        coalesce( a.tdata, b.tdata ) tdata,        c.cdata   from central_table c        left outer join tablea a          on( c.tid = a.ida and              c.tab = 'a' )        left outer join tableb b          on( c.tid = b.idb and              c.tab = 'b' ) 	0.00599755411191055
25303920	32913	mysql query select two tables	select t1.id,count(*) from tab1 t,tab2 t1 where t.id like  concat('%',t1.id, '%') group by t1.na 	0.036610462504756
25312094	15863	mysql select last 'n' records by date, but sorted oldest to newest	select t.* from (     select *     from table     where 1=1     order by table.datefield desc     limit 20 ) t order by t.datefield 	0
25314682	10492	join two table with inner join and two external keys	select u1.username, u2.username,social.val  from social   inner join utenti u1 on u1.id_ut=social.id_ut1  inner join utenti u2 on u2.id_ut=social.id_ut2 	0.0915238084701022
25319959	32844	combine multiple rows in one from same table	select a.itemcode [itemcode], a.storename [store1name],          a.storeprice [store1price],b.storename [store2name],          b.storeprice [store2price],c.storename [store3name],          c.storeprice [store3price] from    tblstoreprice a          left join tblstoreprice b               on a.itemcode = b.itemcode and a.id <> b.id           left join tblstoreprice c               on b.itemcode = c.itemcode and b.id <> c.id and a.id <> c.id 	0
25321997	19357	oracle 10 sql: full join through cross reference table	select    coalesce(n.new_version, x.new_version) as new_version,   n.change_type,    o.original_version,   o.changeid,   o.old_change_type from old_table o  inner join xref_table x    on x.original_version = o.original_version full outer join new_table n    on n.new_version = x.new_version    and n.changeid = o.changeid where coalesce(n.new_version, x.new_version) in ('aaa','bbb','ccc') order by 1,2,3,4,5 ; 	0.419550238486062
25332030	16305	converting string with microseconds to date	select convert(date, '2014-08-15t17:38:22.2930000', 101) select convert(datetime2, '2014-08-15t17:38:22.2930000', 101) 	0.186851420433937
25337580	1098	sql subtracting count(true) from count(false) value	select sum(   (case when status='true' then 1 else -1 end) ) from table 	0.00205648899921706
25358776	13032	sql query for id to filter against date	select distinct ... from `bugtracker`.`mantis_bug_history_table` as `bh` inner join (select bug_id, max(date_modified) md from mantis_bug_history_table group by bug_id) max_dates on bh.bug_id = max_dates.bug_id and bh.date_modified = max_dates.md left join ... 	0.0148391142377641
25365328	27742	select where columnx is less than multiple columns based on row value	select ... where value1 < max(value2, value3, value4, value5, value6) 	0
25375820	37202	mysql select 2 diffrent fields with same value from different lines	select * from orders o1 join orders o2 on o1.id != o2.id and o1.check_in = o2.check_out 	0
25376549	19200	sql: default where clause	select category.foo,         category.bar,         category.baz,         coalesce(category_language.text, default_category_language.text) from admin_real_estate_categories as category  left join admin_real_estate_category_languages as category_language      on category_language.real_estate_category_id = category.id      and category_language.language = 'jp' join admin_real_estate_category_languages as default_category_language      on default_category_language .real_estate_category_id = category.id     and default_category_language.language = 'en' where category.category = 'area' 	0.794801298378851
25394527	27062	show only 2 softwares for each category	select * from (select * from table1 n where ( select count(*) from table1 m where n.categorie = m.categorie and n.id_software <= m.id_software) <= 2 order by n.id_software, n.id_software desc) as tn 	0
25396484	28327	count tuples in mysql	select a, b, count(*) as [count] from table1 group by a, b 	0.0969460862095861
25399878	2136	best way to limit join to only select top 1	select  *  from    moc_links a         outer apply         (select top 1 *          from   moc_log as d          where  d.itemid = a.itemid          order by d.modtime desc) d 	0.00769760579400462
25402156	26848	mysql - union all with queries on same table	select * from  (     (select id, lng from stations where lng >= 18.123 order by lng limit 1)     union all     (select id, lng from stations where lng < 18.123 order by lng limit 1) ) as result12 order by abs(18.123-lng) limit 1; 	0.00251089506249318
25407214	20832	join tables to query for a random row	select * from tableone  where (select count(*) from tabletwo where tabletwo.data_id = tableone.data_id) = 0 order by rand() limit 1 	0.012792068680075
25411139	22811	combining two sql queries in one statement	select m.*, @rank := if(@last = average, @rank, @seq) as rank,         @seq := @seq +1, @last := average from  (   select *, avg(score) as score    from midterm_result    group by student_id ) m order by average desc 	0.0374555922839516
25415095	40520	need help grouping multiple columns into one	select  date(b.tstamp) as "sh date" ,trim(b.number) as "number" ,case when b.report_ts is null then '' else char(date(b.report_ts)) end as "date" ,listagg(f.class, ', ') within group (order by f.class) as "class" ,s.city as "origin city" ,s.state as "origin state" ,s.zipcode as "origin zip" ,c.city as "destination city" ,c.state as "destination state" ,c.zipcode as "destination zip" ,b.weight from af.blue b inner join af.bill f on f.number = b.number and f.correction = b.correction and f.class <> '' inner join af.name s on s.number = b.number and s.correction = b.correction and s.type = 's' inner join af.name c on c.number = b.number and c.correction = b.correction and c.type = 'c' where b.cust = '11111' and (month(current date)-1) = month(b.tstamp) and b.corr = '' group by  date(b.tstamp)  ,trim(b.number)  ,case when b.report_ts is null then '' else char(date(b.report_ts)) end  ,s.city  ,s.state  ,s.zipcode ,c.city  ,c.state  ,c.zipcode ,b.weight 	0.0264906917136361
25416246	27566	mysql nested counts and returning values	select x.pid, p.productdesc, count(x.pid) as count   from (select distinct cl.cid, cl.pid           from client cl           join customer cu             on cl.cid = cu.id          where cu.name in ('smith', 'jones')) x   join products p     on x.pid = p.id  group by x.pid, p.productdesc having count(x.pid) = (select count(*)                          from customer                         where name in ('smith', 'jones')) 	0.223565848599208
25428910	3824	sql query with additional 'nearest' row	select * from test where speed >= 300 union select *  from (     select *     from test     where speed < 300     order by speed desc     limit 1 ) as xxx order by speed 	0.169432989874626
25450172	39742	subscriber dependents table mysql	select s.name as subscriber, d.name as dependent from subscribers s left join dependents d on s.id = d.id     union      select s.name as subscriber, d.name as dependent from subscribers s left join dependents d on s.name = d.name     order by subscriber, dependent 	0.513788797963924
25458214	4922	display two date field value formated like "monthname dd-dd, yyyy"	select date_format(startdate,'%m') + date_format(startdate,'%d') + '-' + date_format(enddate,'%d') + ',' + date_format(startdate,'%y')  from yourtable 	0.000489203835832302
25463662	25863	postgres: how to count distinct elements in array columns given a condition	select id, count(distinct a1) as a1, count(distinct a2) as a2 from (     select id, unnest(array1) as a1, unnest(array2) as a2     from t ) s group by id 	0
25478176	31233	mysql error getting the previous dated record	select * from table where date < (select date from table where ordinal = 5555) order by date desc limit 1; 	0.0160364159867086
25480144	39302	how to find id in a table that is skipped	select l.id + 1 as start from sequence as l   left outer join sequence as r on l.id + 1 = r.id where r.id is null; 	0.000531144986536
25480256	11659	reduce the number of characters in an sql function in oracle database	select c,s,f as f,d as d, v as v from (mysql) union all select c,s,f+(select max(d)-min(d) from mysql)+t.r as f,d+(select max(d)-min(d) from mysql)+t.r as d,0 as v  from (mysql) cross join  ( select rownum r from  dual connect by rownum <= 15 ) t 	0.142807824490508
25484800	7094	select one row and some row in second table	select *, orders.id orders_id, rewinding.id rewinding_id  from orders join rewinding on orders.job_code = rewinding.job_code where orders.job_code = 597 	0
25507025	36782	troublesome character in sql table?	select replace(replace(string,char(10),''),char(13),'') 	0.152593889079659
25511515	9081	how to select a single value from two different tables and divide them	select (cast((select max(row) from tablea) as decimal) / cast((select max(row) from table2) as decimal)) 	0
25514945	34935	matching a value in another table	select t2c1, t2c2, case when t2c2 = (select t1c2 from t1 where (t1c1 = 'a') then '1' else '0' end as selected from t2 	0.000160262060520321
25524942	36542	how to replace the column value in select statement in sql?	select candidateid, case when resumename = '' then 'not available' else 'available' end as availability  from dbo.tbl_candidates  where createdby=userid  order by candidateid desc 	0.0164033143952207
25532098	8704	t-sql: compare 2 columns with unknown values	select [fields] from [table] a  inner join [table] b on a.[family_id] = b.[family_id] where difference(a.[last_name], b.[last_name]) < 4 	0.00252089588177998
25543993	37464	sql query to find local max, min of date based data	select category, grp, min(date) as min_date, max(date) as max_date from (     select category, date          , row_number() over (order by date)           - row_number() over (partition by category order by date) as grp     from t ) as x group by category, grp order by min(date) 	8.92654317467693e-05
25544314	13954	i want to select by the nearest date	select s.qtyavailable from (select s.qtyavailable       from rv_storage st       where st.m_product_id = 1003965           and st.datelastinventory < '1-aug-2014'       order by st.datelastinventory desc) s where rownum = 1 	0.0114183690353719
25553678	13346	combine two mysql queries and subtract the results	select      wa.position,      wa.player,      wa.avg as 'wk_avg',     oa.avg as 'overall_avg',     wa.avg - oa.avg as 'diff' from      (select position, player, sum( points ) / count( distinct year, week ) as  'avg'      from schedule where week = 1 group by player having count( distinct year, week ) >2      ) wa inner join     (select position, player,sum( points ) / count( distinct year, week ) as  'avg'      from schedule group by player having count( distinct year, week ) >2      ) oa on wa.position = oa.position and wa.player = oa.player order by wa.avg - oa.avg desc 	0.00125938658766506
25557150	10490	can't delete primary key on table with fulltext index	select object_id, property_list_id, stoplist_id from sys.fulltext_indexes     where object_id = object_id('mytable'); 	0.470510142922166
25562477	38616	join from multiple tables using where in	select *  from table_1 t1  join table_2 t2  on t1.t1_id  = t2.reft1_id where t1.t1_id in ('12345223', '2343374')  and t2.t2_id in ('2164158194', '3232422423') 	0.0846874752717515
25562885	30258	mysql statement, if at least one row contains result	select t1.* from table as t1 where t1.uniqueid not in(select t.uniqueid from table as t  where t.result="cancelled") 	0.000399370605584398
25566117	11804	ms access - return values by max date	select roleid, actionid, settingid from your_table t1 inner join (    select roleid, actionid, max(date) as mdate    from your_table    group by roleid, actionid ) t2 on t1.roleid = t2.roleid      and t1.actionid = t2.actionid     and t1.date = t2.mdate 	0.015199625318329
25574346	30920	select start date that is 60 business days old	select busdate from      (         select *,         row_number() over (order by date desc) as dayno         from leads.dbo.calendar         where nonbus = 0          and date < cast(getdate() as date)     ) busdays where dayno = 60 	0.000183543073752947
25575856	15467	how to split string in sql server and put it in a table	select left('abcd@123', charindex('@', 'abcd@123')-1),        right('abcd@123', charindex('@', 'abcd@123')-1) 	0.0051354576675216
25604120	20583	selecting a column based on child and parent category	select     c1.name as level1,     c2.name as level2,    c3.name as level3 from categories c1 inner join categories c2    on c2.parentcatid = c1.catid inner join categories c3    on c3.parentcatid = c2.catid where c1.level = 1 and c2.level = 2 and c3.level = 3 and 	0
25609119	40956	get the latest message for each two clients using sql	select *  from chat c where not exists   (select * from chat   where c.fromid in (fromid, toid) and c.toid in (fromid, toid) and c.id < id); 	0
25609313	9005	oracle sql; find same combination of columnvalues in two or more rows	select d.* from (select d.*, count(*) over (partition by sid, rels) as cnt       from draft      ) d where cnt > 1; 	8.13006614058033e-05
25611465	12052	name of customer with highest sale monthwise	select  filter.mn  ,       filter.sum_sales ,       filter.max_sales ,       sales.cust from    (         select  monthname(date) as mn         ,       sum(amt_c) as sum_sales         ,       max(amt_c) as max_sales         from    sales         where   year(date) = year(now())         group by                 mn         ) filter join    sales on      monthname(sales.date) = filter.mn         and sales.amt_c = filter.max_sales 	6.58496231402826e-05
25625172	4110	mysql select column with x words	select * from your_table where length(your_column) - length(replace(your_column, ' ', '')) > 1 	0.00970708423540435
25627324	17797	roll up sparse table in vertica	select session_token, max(col1), max(col2),.., max(coln)        from user_session   group by session_token 	0.775577454074461
25631188	28345	calculate median with sql (db2)	select avg(nodes) from (     select nodes          , row_number() over(order by nodes asc) as rn1          , row_number() over(order by nodes desc) as rn2     from table ) as x(nodes, rn1, rn2) where rn1 in (rn2, rn2 - 1, rn2 + 1) 	0.078616162739601
25633835	26300	how do you check if a cell in one dataset exists in another dataset's variable/column?	select b.var1, a.var2 from a left outer join b on a.var1 = b.var1 	0
25641289	3266	ms sql query min/max/average per day	select cast(datetimefield as date) as date,         min(minreceivembps) as minreceivembps,         max(maxreceivembps) as maxreceivembps,         min(mintransmitmbps) as mintransmitmbps,         max(maxtransmitmbps) as maxtransmitmbps,         avg(avgtransmitmbps) as avgtransmitmbps,         avg(avgreceivembps) as avgreceivembps from cte group by cast(datetimefield as date) 	0.00417189052586565
25649843	32919	display only one record that may or may not have children	select a.[transactionid]       ,a.[filename]       ,a.[destinationsystem]       ,a.[createdon]       ,a.latesterrormessage from ( select [transaction].[transactionid]       ,[filename]       ,[destinationsystem]       ,[createdon]       ,left([transactionerror].[errormessage], 300) as latesterrormessage        ,row_number() over (partition by [transaction].[transactionid] order by [createdon] desc) rn from [wm01db].[dbo].[transaction] inner join sourcesystem    on sourcesystem.sourcesystemid    = [transaction].sourcesystemid                            and   [transaction].createdon >= '2014-08-01 00:00:00.000'                            and   [transaction].createdon <  '2014-09-02 00:00:00.000' left join transactionerror on transactionerror.transactionid = [transaction].transactionid   )a  where a.rn = 1  order by a.[createdon], a.[transactionid] 	0
25664389	30445	mysql address outer query from subquery	select sec_to_time(avg(case when t1.terminatecauseid = 1 then t1.sessiontime end)) as aloc,        concat(truncate(sum(t1.terminatecauseid = 1) * 100 / count(*),                1),              '%') as asr,        count(*) as totalcalls,        sum(t1.terminatecauseid = 1) as terminated1calls,        cast(t1.destination as unsigned) as prefix,        t2.destination as destination,        sec_to_time(sum(case when t1.terminatecauseid = 1 then t1.sessiontime end)) as duration from cc_call t1 inner join      cc_prefix t2      on t1.destination = t2.prefix where t1.card_id = '133' and       t1.starttime >= ('2014-06-1') and t1.starttime <= ('2014-07-01 23:59:59')  group by t1.destination order by duration desc limit 0 , 25; 	0.786728492317031
25689354	25976	mysql select all users except users with @example1.com and @example2.com mails	select *  from `table` where `email` not like '%foo%' and `email` not like '%bar%' and `email` not like '%baz%' 	0.000643365351797086
25689932	18978	firebird how to select ids that match all items in a set	select id from table where label in ('apple', 'pear', 'peach') group by id having count(distinct label)=3 	0
25698353	36851	mysql: select from two tables through a lookup table	select problems.name, solutions.name from problems inner join kadai on kadai.problem = problems.p_index inner join solution on kadai.solution = solutions.s_index where problems.p_index = 2; 	0.000455316788921897
25719978	13939	sql query of sum from 3 tables	select item.id, a.sum_in, b.sum_out, (a.sum_in - b.sum_out) as dif  from item  left outer join( select  id_item as id, sum(number) as sum_in from in   group by id_item) as a on item.id = a.id  left outer join( select  id_item as id, sum(number) as sum_out from out  group by id_item) as b on item.id = b.id 	0.00454996407225043
25722368	32069	does sql automatically associates the id of the subquery inside a row?	select distinct t1.notificationid as id,    (select count(*) from testtable t2    where active = 1          and t2.notificationid = t1.notificationid    ) as getnumber from testtable t1 	0.0141973887425772
25728550	10014	getting an average from counting rows in mysql	select    user_id,    concat(     round(       ( sum(         case when `answer`>0 then 1 else 0 end         ) / count( `answer` )       ) * 100, 2     ),'%'   ) as totals from mydb where answer <>0 group by user_id having count( `answer` ) >99 order by totals desc 	6.16710478969173e-05
25736269	17113	mysql select response missing rows with null values when <> used	select * from t where c1 = 'mike' and (c2 <> 'a' or c2 is null); 	0.192080258796344
25739872	33192	combine field values from different rows	select id ,        stuff(                (select ',' + value                 from mytable a                 where b.id = a.id                 group by a.value                 order by a.value                 for xml path('')), 1 , 1, '') valuess from mytable b group by id; 	0
25748562	21219	mysql: select row order by date with group by	select * from customer_wallet as a inner join (   select max(id) as maxid   from customer_wallet   where credit_balance<0   group by cus_id ) as b on (a.id=b.maxid) 	0.014380736617836
25756236	14818	horizontal average sql view	select      id,     cast((value1+value2+value3) as float)/      (     case when value1>0 then 1 else 0 end     +     case when value2>0 then 1 else 0 end     +     case when value3>0 then 1 else 0 end     )     as avgvalue     from test 	0.0182287019640111
25757076	8423	sql select column with expression	select col1,col2,     case          when @per =1 then (col00+col01)          when @per =2 then (col00+col01+col02)         when @per =3 then (col00+col01+col02+col03)     end as cola from tablex 	0.557099556720192
25767564	20333	aggregating 15-minute data into weekly values	select name, week, avg(parameter1), avg(parameter2) from data where week in ('29','30','31','32') group by name, week order by name 	0.00153392379804998
25781416	22771	sql query to combine two rows into one as result	select t1.*, t2.* from table1 t1 inner join table1 t2 on t1.refid = t2.id and t1.id < t2.id where t1.id is not null 	8.32043204856293e-05
25794226	8233	how to query two fields (different) into one field	select distinct master.item from master left join [size list] master.[item] = [size list].[item] where [size list].subitem is  null union select distinct [size list].subitem from    [size list] 	0
25799401	20871	mysql query two tables and max timestamp	select table_conversations.conversation_id, table_conversations.contact_number,        table_conversations.contact_id, max(table_messages.timestamp)  from table_conversations join table_messages on table_conversations.conversation_id = table_messages.conversation_id where table_conversations.status='active'  and table_messages.status='active'  group by contact_number  order by table_messages.timestamp; 	0.00442059638482963
25804039	32354	return value not currently assigned from mysql database	select *  from teams  where teamid not in (     select teamid      from leagueinformation      where leagueid = 1 and seasonid = 1 ) 	0.00306843282403062
25827676	4535	best way to select 2 tables mysql	select post.id as post_id, group_concat(images.image) as images from post join images on images.post = post.id group by post.id order by post.id 	0.0208607967622801
