3839	485	how do i concatenate entire result sets in mysql?	select a,b,c, "query 1" as origin from table where field like 'query%'unionselect a,b,c, "query 2" as origin from table where field like '%query'unionselect a,b,c, "query 3" as origin from table where field like '%query%'group by origin, b order by origin, b asc limit 5 	0.00153281198037118
6899	35923	is there a way to create a sql server function to "join" multiple rows from a subquery into a single delimited field?	select [vehicleid]      , [name]      , (select cast(city + ', ' as varchar(max))           from [location]           where (vehicleid = vehicle.vehicleid)           for xml path ('')       ) as locations from [vehicle] 	0.00128555578982821
8145	2766	how do i find the high water mark (for sessions) on oracle 9i	select sessions_highwater from v$license; 	0.0385806229663605
32100	825	what is the simplest sql query to find the second largest value?	select max( col )   from table  where col < ( select max( col )                  from table ) 	0.000473478573808762
36760	34564	sql query, count with 0 count	select page.name, count(page-attachment.id) as attachmentsnumber  from page      left outer join page-attachment on page.id=page-id  group by page.name 	0.382803772936834
37696	4906	concatenate several fields into one with sql	select pagetag.id, page.name, group_concat(tag.name) from  (page left join pagetag on page.id = pagetag.pageid)  left join tag on pagetag.tagid = tag.id group by page.id; 	0.00028342329058052
39243	6652	query to identify the number of revisions made to a table	select * from sys.objects where type='u' 	0.00161626354825924
49602	12637	how to limit result set size for arbitrary query in ingres?	select first 10 * from mytable 	0.0442784865053372
52822	10513	how to import a dbf file in sql server	select * into sometable from openrowset('msdasql', 'driver=microsoft visual foxpro driver; sourcedb=\\someserver\somepath\; sourcetype=dbf', 'select * from somedbf') 	0.182474045814229
85036	9857	how can i quickly identify most recently modified stored procedures in sql server	select name,create_date,modify_date from sys.procedures order by modify_date desc 	0.0410966574042466
94930	31253	fetch one row per account id from list	select top 10 accountid, score from scores s1 where accountid not in      (select accountid s2 from scores       where s1.accountid = s2.accountid and s1.score > s2.score) order by score desc 	0
95967	32384	how do you list the primary key of a sql server table?	select col.column_name from      information_schema.table_constraints tab,      information_schema.constraint_column_usage col  where      col.constraint_name = tab.constraint_name     and col.table_name = tab.table_name     and constraint_type = 'primary key'     and col.table_name = '<your table name>' 	0.00032280847313387
104971	13632	sql query help: selecting rows that appear a certain number of times	select dates    from table t   group by dates having count(dates) < k ; 	0
106323	8136	sqlplus settings to generate tab-separated data file	select chr(9) from dual; 	0.127608019015871
113916	31907	how do i find out what collations are available in sql 2000/2005	select distinct collation_name from information_schema.columns order by 1 	0.0557873277298582
119679	31905	list of stored procedure from table	select   so.name,   sc.text from   sysobjects so inner join syscomments sc on so.id = sc.id where   sc.text like '%insert into xyz%'   or sc.text like '%update xyz%' 	0.00478420104843132
149772	2863	how to use group by to concatenate strings in mysql?	select id, group_concat(string separator ' ') from table group by id; 	0.0347518057543245
151195	2829	possible to use sql to sort by date but put null dates at the back of the results set?	select * from mytable where ... order by case when mydate is null then 1 else 0 end, mydate; 	0
163887	11983	sql query: simulating an "and" over several rows instead of sub-querying	select contentid from tags where tagid in (334, 338, 342) group by contentid having count(distinct tagid) = 3 select contentid from tags where tagid in (...)  group by contentid having count(distinct tagid) = ...  	0.0180951884214145
169784	41159	not getting the correct count in sql	select count(isnull(col1,0)) from   table1 	0.390803540708286
174532	36057	how to find "holes" in a table	select id +1 from table t1 where not exists (select * from table t2 where t1.id +1 = t2.id); 	0.00756974332122459
177956	28709	what is the best way to convert an int or null to boolean value in an sql query?	select      case when valuecolumn is null then 'false' else 'true' end booleanoutput  from      table 	0.718594945797945
186942	26062	generate multiple and filtered drop + create stored procedures	select object_definition(object_id), 'drop procedure [' + name + ']' from   sys.procedures where modify_date >= @date 	0.127828922684488
187998	27186	row offset in sql server	select col1, col2  from (     select col1, col2, row_number() over (order by id) as rownum     from mytable ) as myderivedtable where myderivedtable.rownum between @startrow and @endrow 	0.134650337832438
197111	33028	fastest "get duplicates" sql script	select afield1,count(afield1) from atable  group by afield1 having count(afield1) > 1 	0.0636092087070613
201621	39060	how do i see all foreign keys to a table or column?	select   table_name,column_name,constraint_name, referenced_table_name,referenced_column_name from information_schema.key_column_usage where   referenced_table_name = '<table>'; 	0
208925	30430	is there a difference between select * and select [list each col]	select col1, col2 from table 	0
224295	31478	how do i get count of duplicated values and join the table to retrieve each value's name?	select venues.venue_name, count(*) as volunteer_count from venues left outer join volunteers    on venues.id = volunteers.venue_id group by venues.venue_name 	0
243035	11981	finding difference in row count of two tables in mysql	select inv_t.product_id, inventory_total-nvl(sales_total,0) from    (select product_id, sum(quantity) as inventory_total    from inventory    group by product_id) inv_t left outer join   (select product_id, count(*) as sales_total     from sales     group by product_id) sale_t   on (inv_t.product_id = sale_t.product_id) 	0
243567	36845	remove duplicate from a table	select field1, field2, field3, count(*)  into temp_table1 from table1 group by field1, field2, field3 having count(*) > 1 delete t1 from table1 t1 inner join (select field1, field2, field3       from table1       group by field1, field2, field3 having count(*) > 1) sq on             sq.field1 = t1.field1 and             sq.field2 = t1.field2 and             sq.field3 = t1.field3 insert into table1 (field1, field2, field3) select field1, field2, field3 from temp_table1 drop table temp_table1 	0.000595854307947204
248683	29323	how can i do boolean logic on two columns in mysql?	select (payment1_paid && payment2_paid) as paid_in_full  from denormalized_payments  where payment1_type = 'check'; 	0.0439117810911191
248990	32750	summarize aggregated data	select softwarename,    sum( case country when 'canada' then [count] else 0 end ) as canada,   sum( case country when 'usa'    then [count] else 0 end ) as usa,   sum( [count] ) as total from [table]  group by softwarename; 	0.0962938245085309
254216	37754	joining two tables without returning unwanted row	select    issueid,    assignedid,    creatorid,    assigneduser.real_name as assignedname,    creatoruser.real_name as creatorname from issues   left join users as assigneduser          on issues.assignedid = assigneduser.userid   left join users as creatoruser          on issues.creatorid = creatoruser.userid order by `issueid` asc limit 0, 30 	0.0159898650880056
331367	19460	sql statement help - select latest order for each customer	select *  from customers inner join orders  on customers.customerid = orders.customerid and orderid = (select top 1 suborders.orderid                      from orders suborders                      where suborders.customerid = orders.customerid                      order by suborders.orderdate desc) 	0.000455003436691879
341074	14812	urlencode with only built-in functions	select regexp_replace(encode('héllo there','hex'),'(..)',e'%\\1','g'); 	0.780325736331889
354035	17446	sql server deadlock object ids are too large	select hobt_id, object_name(p.[object_id]), index_id  from sys.partitions p  where hobt_id = 72057594060734464 	0.720691753221527
355526	27390	access query: how to query to get calculated values?	select t.type, t.code, count(t.code) as countofcode,    [countofcode]/dcount("code","t","code=" & [code])*100 as percentcode,    [countofcode]/dcount("type","t","type=" & [type])*100 as percenttype       from t       group by t.type, t.code 	0.0173882521838751
356578	26	how to output mysql query results in csv format?	select order_id,product_name,qty from orders into outfile '/tmp/orders.csv' fields terminated by ',' enclosed by '"' lines terminated by '\n' 	0.142151295362699
358687	35807	unaccounted for database size	select object_name(object_id)  as name, rows,  total_pages,    total_pages * 8192 / 1024 as [size(kb)] from sys.partitions p inner join sys.allocation_units a   on p.partition_id = a.container_id 	0.132512347378783
359257	24584	why is 30 the default length for varchar when using cast?	select cast('the quick brown fox jumped over the lazy dog' as varchar(45)) 	0.725185843966443
361455	34666	subtraction of mysql times inconsistent on different machines	select time(c.start_time),        time(c.end_time),        extract(hour from timediff(time(c.end_time), time(c.start_time)))          as 'opening_hours'  from my_shop c; 	0.0244296429109685
400712	23215	how to do equivalent of "limit distinct"?	select * from table where client_id in  (select distinct client_id from table order by client_id limit 5) 	0.412032722227299
403630	33037	using full-text search in sql server 2008 across multiple tables, columns	select b.name, a.name, bkt.[rank] + akt.[rank]/2 as [rank] from book b inner join author a on b.authorid = a.authorid inner join freetexttable(book, name, @criteria) bkt on b.contentid = bkt.[key]  left join freetexttable(author, name, @criteria) akt on a.authorid = akt.[key] order by [rank] desc 	0.330485282248601
419476	6921	sql query advice - get previous item	select curr.prodid, curr.publishdate as currentissue, prev.publishdate as previssue from issues curr, issues prev where prodid=123 and curr.publishdate='12/06/2008' and prev.issueid=curr.issueid - 1 	0.012341046287633
438610	36760	how do i write a query that outputs the row number as a column?	select row_number() over (order by beatle_name asc) as rowid, * from beatles 	0.000810209394599092
438711	2521	selecting from multiple mysql tables	select t1.name1 as name from table1 union select t2.name2 as name from table2 	0.00193743339068103
438938	27474	sql server: only last entry in group by	select      t1.id,      t1.business_key,      t1.result from      dbo.my_table t1 left outer join dbo.my_table t2 on      t2.business_key = t1.business_key and      t2.id > t1.id where      t2.id is null 	0.000152668306787374
452464	6100	how can i get column names from a table?	select table_name, column_name, data_type, data_length from user_tab_columns where table_name = 'mytable' 	0
495814	37680	how do i write some sql that will return results showing the number of rows that occured in each hourly period?	select datepart(hh, datetimecolumn), count(*) from     tablename group by     datepart(hh, datetimecolumn) order by     datepart(hh, datetimecolumn) 	0
497317	24982	how can i view all grants for an sql database?	select      class_desc    , case when class = 0 then db_name()          when class = 1 then object_name(major_id)          when class = 3 then schema_name(major_id) end [securable]   , user_name(grantee_principal_id) [user]   , permission_name   , state_desc from sys.database_permissions 	0.248041138654541
502794	8752	sql - min() gets the lowest value, max() the highest, what if i want the 2nd (or 5th or nth) lowest value?	select  * from    (     select a_id, (      select b_id      from mytable mib      where mib.a_id = ma.a_id      order by       dist desc      limit 1 offset s      ) as b_id     from (      select distinct a_id      from mytable mia      ) ma, generate_series (1, 10) s     ) ab where   b_id is not null 	0
519876	25878	sql formatting standards	select     st.columnname1,     jt.columnname2,     sjt.columnname3 from      sourcetable st inner join jointable jt on      jt.sourcetableid = st.sourcetableid inner join secondjointable sjt on      st.sourcetableid = sjt.sourcetableid where         st.sourcetableid = x     and jt.columnname3 = y     and jt.column3 = sjt.column4 	0.796971124622676
523507	29031	sql left join and duplicates in result	select a.id aid, group_concat(distinct b.id) bid from a left join b on b.aid = a.id where a.id = 1 group by a.id 	0.75854945775506
559891	17843	best way to calculate dates from results?	select distinct date from table 	0.000770815183229372
578418	19633	query to fetch mssql table unique index and primary keys	select s2.xtype, syscolumns.name, sysindexkeys.indid, sysobjects.type from     syscolumns left join sysobjects on syscolumns.id = sysobjects.id left join sysindexkeys on (      syscolumns.id = sysindexkeys.id and syscolumns.colid = sysindexkeys.colid ) join sysobjects s2 on s2.parent_obj = sysindexkeys.id where sysobjects.name = '{$table}' and s2.type = 'k' and sysindexkeys.indid is not null order by sysindexkeys.indid, sysindexkeys.keyno 	0.00135482593476245
586773	35958	is there a way to calculate time differences in mysql using one select	select timediff( date2 ,date1) from example_table where id=1; 	0.000617479102192965
600446	38718	sql server: how do you return the column names from a table?	select column_name,*  from information_schema.columns where table_name = 'yourtablename' and table_schema='yourschemaname' 	6.26140709644266e-05
606751	11874	convert integer to a list of week days	select   ( case when daybits & 1 = 1 then 'sunday ' else '' end ) +   ( case when daybits & 2 = 2 then 'monday ' else '' end ) +   ( case when daybits & 4 = 4 then 'tuesday ' else '' end ) +   ...   ( case when daybits & 64 = 64 then 'saturday ' else '' end ) + 	0
625055	11638	subquery to return the latest entry for each parent id	select d.id, d.name, h.last_user_id     from documents d left join          (select r.doc_id as id, user_id as last_user_id               from history r join                    (select doc_id, max("timestamp") as "timestamp"                         from history                         group by doc_id                    ) as l                    on  r."timestamp" = l."timestamp"                    and r.doc_id      = l.doc_id          ) as h          on d.id = h.id 	0
638065	6211	selecting subsequent records arbitrarily with limit	select * from mytable where datecolumn > (select datecolumn from mytable where id = @id) order by datecolumn limit 1 	0.0133218326062562
647908	40576	sql, order by - how to give more authority to other columns?	select * from converts  where email='myemail@googlemail.com' and status!='1'  order by floor(unix_timestamp(date)/600) asc, priority desc 	0.00461070300123374
648377	16482	merging tables in access	select t1.id, t1.a, t1.b, t1.c, t2.d, t2.e, t2.f  into t0 from t1 inner join t2 on t1.id = t2.id; 	0.0659664831162257
659504	8613	is there a simple way to query the children of a node?	select node.name, (count(parent.name) - (sub_tree.depth + 1)) as depth from nested_category as node,     nested_category as parent,     nested_category as sub_parent,     (         select node.name, (count(parent.name) - 1) as depth         from nested_category as node,         nested_category as parent         where node.lft between parent.lft and parent.rgt         and node.name = 'portable electronics'         group by node.name         order by node.lft     )as sub_tree where node.lft between parent.lft and parent.rgt     and node.lft between sub_parent.lft and sub_parent.rgt     and sub_parent.name = sub_tree.name group by node.name having depth <= 1 order by node.lft; 	0.0796710204905044
698377	7565	count datediff exceeding a specified value	select count(*)  from task_conditionassessment t  where datediff(dd,t.nextduedate,@enddate) > 14 	0.0374659047580022
710179	17732	how can i select distinct rows when a text field is part of the returned fields in ms sql server 2000?	select s.id, s.title, s.desc from section as s  where exists (select * from quest-ans as q where q.sec_id = s.id) 	0.00094177879189243
713677	39133	can a ms/transact-sql stored procedure look up its own name?	select object_name(@@procid) 	0.101545905109721
723486	12718	t-sql for combining 2 columns' values into one with "replicate"	select substring(replicate(','+cast(reps as varchar),sets),2,8000) as reps from table 	0.000542772608566927
726993	30412	sql trigger - which table does it belong to?	select     object_name(parent_id) as [table],     object_name(object_id) as triggername from     sys.triggers where     object_id = @@procid 	0.275838025839204
728833	348	convert a string to int using sql query	select cast(myvarcharcol as int) from table select convert(int, myvarcharcol) from table 	0.272916937120828
729488	9208	sql: counting number of occurances over multiple columns in oracle	select  userid, service, count(userid) timesaccessed from    table group by userid, service 	0.00041741535250027
733979	18233	selecting all rows until first occurence of given value	select * from mytable where date > (    select max(date) from mytable where check = 0     ) 	0
739143	28211	how do i find the most common result in a column in my mysql table	select count(*) as `rows`, userid from `postings` group by userid order by `rows` desc limit 1 	0
758346	38902	ordering a table in mysql, according to another, but without seeing repetitive rows of the first table	select     a.id, a.question, a.roundid, a.phase,     users.username, users.id,     max(b.id) as latest  from     a, users, b  where     a.phase = 0 and users.id = a.usercreatorid and b.experimentid = a.id  group by a.id order by latest desc 	0
778355	39087	when did oracle start supporting "top": select top ? p2_.product_id from product?	select  *   from  (select  *            from  foo           where  foo_id=[number]        order by  foo_id desc)  where  rownum <= 3 	0.00379431157994887
784607	38305	sql strict enforce of order by a date column	select a, c from tablea where a >=0 order by c asc, a asc, b asc, d asc 	0.0114184602775874
792357	8099	max count together in an sql query 2	select t.id,        t.description as most_popular_description,        count(*) as times_the_desc_appeared_for_an_id from mytable t inner join (   select id, stats_mode(description) as desc from mytable group by id ) a on t.id = a.id and t.description = a.desc group by t.id, t.description; 	0.0849404946507285
809705	15597	select average value and distinct values sql	select state, avg(lat), avg(lon)  from trealtytrac  group by state  order by state 	0.00018595148469239
809916	9465	best practice for comment voting database structure	select sum(votevalue) from votes where commentid = ? 	0.321760216017103
812675	32372	sum different row in column based on second column value	select   salespersonid,   sum(     case currencyid       when 1 then saleamount       else 0     end   ) as totalcad,   sum(     case currencyid       when 2 then saleamount       else 0     end   ) as totalusd from orders group by salespersonid 	0
876842	1607	how to find the average time difference between rows in a table?	select timestampdiff(second, min(ts), max(ts) )         /        (count(distinct(ts)) -1)  from t 	0
883383	29814	subqueries in ms access: selecting only one record per "person" per date	select readings_miu_id     , reading , readdate , readtime     , miuwindow, sn, noise, rssi     , origincol, colid, ownage   from analyzed as a     where analyzed.readdate between #4/21/2009# and #4/29/2009#         and analyzed.readtime=           (select top 1 analyzed.readtime from analyzed               where analyzed.readings_miu_id = a.readings_miu_id                  and analyzed.readdate = a.readdate              order by analyzed.readtime desc); 	0
903924	1111	random values from db in c#	select top n         somecolumn  from          sometable order by          checksum(newid()) 	0.00354567356162532
905080	8992	how do i sort into a dynamically generated specific order in mysql?	select images.* from images inner join productphotos on images.imageid = productphotos.imageid where productid in (5, 2, 4) order by field(specificproductuid, 5,2,4); 	0.00313937778454592
925296	35694	sql query for retrieving search results	select widgetid from widget inner join widgetattributes wa on wa.key = searchattributes.key and wa.widgetid = widget.widgetid group by widgetid having count(widget.widgetid) > @searchattributescount 	0.16698664994935
929060	9409	sql: select the highest conditional sum on a table	select product_id, sum(quantity) as productqtysum from ordersproducts  group by product_id  order by productqtysum desc 	0.00103058248844616
944173	34132	mysql join sum column on the whole table	select  t.*, idsum from    (         select  sum(id) as idsum         from    mytable         ) q,         mytable t 	0.00614109798451587
947281	15165	multiple column pivot in t-sql	select    field1 , [1] = max(case when rowid = 1 then field2 end) , [2] = max(case when rowid = 2 then field2 end) , [3] = max(case when rowid = 3 then field2 end) , [4] = max(case when rowid = 4 then field2 end) from (   select      field1   , field2   , rowid = row_number() over (partition by field1 order by field2)   from tblname   ) sourcetable group by    field1 	0.263314910114377
964288	11742	flattening intersecting timespans	select      st.start_time,      et.end_time from (      select           t1.start_time      from           dbo.test_time_spans t1      left outer join dbo.test_time_spans t2 on           t2.start_time < t1.start_time and           t2.end_time >= t1.start_time      where           t2.start_time is null ) as st inner join (      select           t3.end_time      from           dbo.test_time_spans t3      left outer join dbo.test_time_spans t4 on           t4.end_time > t3.end_time and           t4.start_time <= t3.end_time      where           t4.start_time is null ) as et on      et.end_time > st.start_time left outer join (      select           t5.end_time      from           dbo.test_time_spans t5      left outer join dbo.test_time_spans t6 on           t6.end_time > t5.end_time and           t6.start_time <= t5.end_time      where           t6.start_time is null ) as et2 on      et2.end_time > st.start_time and      et2.end_time < et.end_time where      et2.end_time is null 	0.348759080190134
966176	554	select distinct on one column	select  * from    (select id, sku, product,                 row_number() over (partition by product order by id) as rownumber          from   mytable          where  sku like 'foo%') as a where   a.rownumber = 1 	0.00218216642458741
975628	5992	how do i write a sql statement with mutliple test and tables?	select date from media_comment mc join media m on m.mediaid = mc.mediaid where mc.author = @userid and mc.date > @date and ((mc.parentid = 0 and m.userid != @userid)  or (exists select 1 from media_comment mc2 where mc.parentid = mc2.id and mc2.author = mc.author)) 	0.704735870564125
987389	6868	sql max() question	select uid, timestamp  from node_revisions  where timestamp = (select max(timestamp) from node_revisions); 	0.752379552150922
990226	35665	finding bigram in a location index	select concat(i.wordid, "|", j.wordid) as bigram, count(*) as freq from index as i, index as j where j.location = i.location+1 and        j.docid = i.docid group by bigram order by freq desc 	0.0481425561151676
995373	38985	mysql: sort group_concat values	select student_name,   group_concat(distinct test_score order by test_score desc separator ' ')   from student   group by student_name; 	0.113929025246491
996899	35875	sql union all to display old data with new data?	select     tblatraining.fldtid,     tblatraining.fldtcrsid,     tblatraining.fldtlocabr,     tblatraining.fldtdatestart,     tblatraining.fldtdatestart,     tblatraining.fldtdateend,     tblatraining.fldtenrolled,     tblatraining.fldtpid     union all     tblatrainingarchive.fldtid,     tblatrainingarchive.fldtcrsid,     tblatrainingarchive.fldtlocabr,     tblatrainingarchive.fldtdatestart,     tblatrainingarchive.fldtdatestart,     tblatrainingarchive.fldtdateend,     tblatrainingarchive.fldtenrolled,     tblatrainingarchive.fldtpid 	0.000237566226193847
1002349	31187	using distinct and count together in a mysql query	select count(distinct productid) from  table_name where keyword='$keyword' 	0.187184370008371
1002452	7804	mysql: select distinct from 2 different tables?	select distinct product_type from (     select product_type from table 1     union      select procut_type from table 2 ) t 	0.000187212687670425
1004079	32884	selecting the top n rows within a group by clause	select     bar1.instrument     ,bar2.* from (     select distinct instrument from bar) as bar1 cross apply (     select top 5      bar2.instrument      ,bar2.bar_dttm      ,bar2.bar_open      ,bar2.bar_close      from bar as bar2 where bar2.instrument = bar1.instrument) as bar2 	0.000141553460495649
1010898	7728	how to find current open cursors in oracle	select a.value, s.username, s.sid, s.serial# from v$sesstat a, v$statname b, v$session s where a.statistic# = b.statistic#  and s.sid=a.sid and b.name = 'opened cursors current'; 	0.00607709641503815
1015165	16779	group-by/aggregation over date ranges	select count(*), to_char('yyyy-mm-dd', created) from abc group by to_char('yyyy-mm-dd', created) 	0.0110876703621935
1038590	32313	sql - check table for new rows?	select name, color from tablea where not exists ( select 1 from tableb where tablea.name = tableb.name  and tablea.color = tableb.color) 	0.00197839391435746
1070032	39158	sql join over five tables	select   m.name as model_name,   c.countryname,   count(*) as network_count from   models                        as  m   inner join models_networks    as mn on mn.model_id = m.id   inner join networks           as  n on n.id = mn.network_id   inner join countries_networks as cn on cn.network_id = n.id   inner join countries          as  c on c.id = cn.country_id where   c.countryname = 'france' group by   m.name,   c.countryname 	0.196264541259341
1079480	12440	how to determine position of row in sql result-set?	select      t1.id,             t1.[name],             (select count(*)               from table t2               where t2.[name] < t1.[name]) + 1 as rowpos from        table t1 order by    t1.[name] 	0.000761331882404553
1085973	29092	select most recent dates	select t1.mrmatter,t2.mrtk,t1.mrrate,t2.mostrecent from mexrate t1 inner join (     select distinct(mrtk),max(mreffdate) as mostrecent     from mexrate     where mrmatter='184866-00111'         group by mrtk ) t2 on t1.mrtk=t2.mrtk and t1.mreffdate=t2.mostrecent where mrmatter='184866-00111' 	0.000195305709065281
1092925	16351	how to minimize the load in queries that need grouping with different invervals?	select count(*) as count, sum(important_data) as important_data, date_format('%y-%m', date) as month   from my_table    where date between ? and ?    group by  date_format('%y-%m', date)   order by date desc; 	0.0404903256023157
1103540	37648	sql calculate difference between cell values	select    tablea.a1 - tableb.a1 as a1,   tablea.b1 - tableb.b1 as b1 from tablea, tableb 	8.60124772844565e-05
1107919	5304	mysql: sum subqueried columns	select @query1:=(subquery) as s1, @query2:=(subquery) as s2, (@query1+@query2) as s3 	0.0263084238472496
1110345	21722	unexpected duplication in mysqli/php	select answers.id, answers.answer from answers, a_lookup, questions where  answers.id=a_lookup.a_id and '$i'=a_lookup.q_id and '$i' = questions.id; 	0.700566613396535
1110998	36286	get day of week in sql 2005/2008	select datename(dw,getdate())  select datepart(dw,getdate())  	0
1114772	29911	sql query with multiple "in" on same many-to-many table	select "products_product"."id","products_product"."name", from "products_product" where (     exists (select 1 from "products_ingridientproductbound" where "products_product"."id" = "products_ingridientproductbound"."product_id" and "products_ingridientproductbound"."ingridient_id" in (16, 17, 18, 19))      and     exists (select 1 from "products_ingridientproductbound" where "products_product"."id" = "products_ingridientproductbound"."product_id" and "products_ingridientproductbound"."ingridient_id" in (43, 44, 45)) ) limit 21 	0.025825704841435
1122409	39280	how can a stored proc retrieve the name of the database it's running in?	select db_name() 	0.000831303287675307
1143514	13640	sql server 2005 joining results of two different sp like 	select * from dbo.myfunction1(p1)  union select * from dbo.myfunction2(p2) 	0.713439438678256
1160512	21038	add results from several count queries	select ( select count(*) from comments )       + ( select count(*) from tags )       + ( select count(*) from search ) 	0.00499726806638572
1179913	6841	mysql: group and sum from different tables. help!	select dt.id      , dt.type      , dt.points + coalesce(t2.epoints, t3.epoints) as points   from (select t1.id              , t1.type              , sum(t1.points) as points           from t1         group             by t1.id) as dt left outer   join t2     on t2.type = dt.type left outer   join t3     on t3.type = dt.type 	0.025271356664786
1180507	1180	sql query for commissions (decision?) table	select comm from yourtable    where profit between yourtable.profitstartrange and yourtable.profitendrange 	0.412295904274123
1191462	10285	mysql weekday/weekend count - part ii	select    fname,    month(eventdate),    sum(if(weekday(eventdate) < 5,1,0)) as weekdaycount,   sum(if(weekday(eventdate) >= 5,1,0)) as weekendcount from eventcal as e left join users as u on e.primary = u.username group by fname, month(eventdate); 	0.582915821502426
1218738	11706	show number of visits in the last 24 hours, broken down by the hour	select hour(added), count(*) as nbr from visits where added between '2009-07-14' and '2009-07-15' group by hour(added) order by hour(added) 	0
1219261	7424	t-sql: selecting top n characters from a text or ntext column	select top 10     c.firstname + ' ' + c.lastname as customername     ,substring(c.testimonialtext,1,50) as testimonialsnippet     ,c.testimonialdate from customer as c   order by substring(c.testimonialtext,1,50) desc 	0.00056340469361259
1232390	3375	how do i find out the host for the local sql 2005 server?	select host_name() 	0.10814478312144
1244028	5903	sql order by list of strings?	select * from table order by (      case code       when 'health' then 0       when 'phone' then 1      when 'freeze' then 2      when 'hot' then 3      end ) 	0.0270611187866491
1251799	17066	how to determine what row contains a specific decimal is in a sql column	select * from myrows where (myval - cast(myval as integer)) = 0.002; 	0.000608301817647412
1252053	39212	sorting records in a 1:n (one-to-many) relationship	select * from persons  left outer join photos on person.id=photos.person_id order by photos.title 	0.0207717401985705
1267886	3832	mysql join on similar columns	select  * from    table1 t1 join    table2 t2 on      t2.name = concat('e', t1.name) 	0.0495088311033371
1309203	13797	order by sum of two fields	select  id, karma_up, karma_down, (karma_up-karma_down) as user_karma  from karma  order by user_karma desc 	0.00360322016440011
1316938	35806	sql - how to use sum and max in same query?	select item_id, sum(vote_value) as sum from votes group by item_id order by sum desc limit 1 	0.0437999599178743
1349322	33570	how can i join these two queries?	select posts.*, users.authorname as author,        group_concat(categories.category) as categories   from posts, users, categories, post_category  where users.id = posts.author    and post_category.categoryid = categories.id    and post_category.postid = posts.id  group by posts.* , author 	0.251748861383217
1349357	19426	how to determine a primary key for a table in sql server?	select i.name as indexname,  object_name(ic.object_id) as tablename,  col_name(ic.object_id,ic.column_id) as columnname,  c.is_identity, c.user_type_id, cast(c.max_length as int) as max_length, cast(c.precision as int) as precision, cast(c.scale as int) as scale  from sys.indexes as i  inner join sys.index_columns as ic  inner join sys.columns as c on ic.object_id = c.object_id and ic.column_id = c.column_id  on i.object_id = ic.object_id  and i.index_id = ic.index_id  where i.is_primary_key = 1 and ic.object_id = object_id('dbo.yourtablenamehere') order by object_name(ic.object_id), ic.key_ordinal 	0.00355679012946261
1356073	35950	sql statement to order rows by so children follow each parent	select id, name from category order by (parentid * 10000) + id 	0.000238548778163703
1388492	40826	how can i search mysql for a single date?	select foo from mytable where to_days(timestamp) = to_days('2009-09-07'); 	0.0224783886487349
1390740	37019	selecting minimum from a query with group by	select a.topicid, d.catalogfileid, d.catalogfileextension, a.sortorder from catalog_topics a left join catalog_files_join b on a.catalogid = b.foreignkey left join catalog_files_join c on c.foreignkey = b.catalogfileid left join catalog_files d on d.catalogfileid = b.catalogfileid where b.filetypeid = 'gvl401' and c.filetypeid = 'gvl25' and a.topicid = 'top340' order by a.sortorder asc limit 1 	0.00249896394062182
1395329	29320	can layered subqueries spanning multiple tables reference a parent query?	select post_id, count(distinct user_id) from  (     select id as post_id, user_id from posts     union     select post_id, user_id from discussions     union      select post_id, user_id from comments ) a group by post_id 	0.167183743831259
1399321	37324	how to check, if a value is an integer with plpgsql?	select  current_setting('myvar.user') ~ '^[0-9]+$' 	0.0130027811696707
1399708	5236	sql server: select parent-child	select id, name, parentid from productcategories order by coalesce(parentid, id),     coalesce(parentid, 0), name 	0.7072261701051
1405932	37975	problems counting joined rows with conditional	select count( tasks.task_id ) as task_count,         projects.* from (projects) left join tasks on tasks.project_id = projects.project_id and tasks.status < 9 and tasks.assigned_user_id = '1' left join projects_to_users on projects.project_id=projects_to_users.project_id and projects_to_users.user_id = '1' group by projects.project_id 	0.487958444105871
1423159	12354	select rows from a table with date in the region- 90days ago and now.?	select d.id, d.name, d.gameinfo,   avg(r.rating) as avgrating, count(r.rating) as count from gamedata d left join gameratingstblx245v r on (d.id = r.game_id) where d.releasedate between now() - interval 90 day and now() group by d.id  order by avgrating desc limit 0,8; 	0
1432722	24605	tsql: get letter representation for a number	select char(64+6) 	0.000271711360389849
1435191	16043	sql order results by number of fields matched	select     ....     from ....     order by         (case when field1 = 'variable 1' then 1000 else 0 end         +case when field2 = 'variable 2' then 800 else 0 end         +case when field3 = 'variable 3' then 600 else 0 end         +case when field4 = 'variable 4' then 10 else 0 end         +case when field5 = 'variable 5' then 1 else 0 end         ) desc 	0.00133085595445366
1440669	28080	grabbing most recent row based on column with repeating data?	select * from myrecords t1  where c = (select max(c) from myrecords t2 where t2.b = t1.b) 	0
1459269	23574	oracle group by and the empty resulting set	select  change_ticket.status, nvl(sum(service_req), 0) as sum_req  from change_ticket, change where change.company_id (+) = '0'    and change.month (+)='07'   and change.id  (+) = change_ticket.change_id  group by change_ticket.status union all select '' as status, 0 as sum_req from dual where not exists (select null from change_ticket) 	0.0478078986025751
1464991	6407	to get total number of columns in a table in sql	select count(column_name) from information_schema.columns where  table_catalog = 'database' and table_schema = 'dbo' and table_name = 'table' 	0
1469506	4863	sql: how do write the order by based on value within a group?	select t.project, t.issues, t.updated from t join (select project, max(updated) as dat       from t group by project) as t1   on (t.project = t1.project) order by t1.dat desc, t.issues asc 	0.00119439007895123
1481236	28816	working with time portion of a datetime column in sql server2008	select dateadd(hh,-1,getdate()) 	0.0247911586614122
1482115	5229	doing a count mysql query?	select uid,     count(case when type='product' then 1 else null end) as product,     count(case when type='service' then 1 else null end) as service,     count(case when type='invoice' then 1 else null end) as invoice,     count(case when type='order' then 1 else null end) as order from mytable group by uid order by uid 	0.599741917636421
1484298	4985	finding record in mysql table that has the highest value	select * from map where positionv = (select max(positionv) from map) 	0
1505466	33944	how do i query xml stored as text?	select id,    cast(request as xml) as requestxml,   cast(request as xml) as responsetxml,   merchantid,   amount from <table> 	0.618449634235475
1509625	8828	refine your search with total amount on each item. php with mysql	select t2.tag, count(*) from so_posts p1 join post_tags t1 on p.postid = t1.postid join post_tags t2 on p.postid = t2.postid group by t2.tag where t1.tag = 'php' order by count(*) desc 	0
1523346	31319	select inbetween elements in mysql?	select * from users limit 10 offset 10 (or 20, or 30); 	0.0768240498541643
1528688	18376	mysql count return zero if no record found	select cities.city_name, count(properties.id_city)   from cities left join properties on cities.id_city = properties.id_city   group by 1 	0.00101204965189594
1540246	15109	sql join puzzler	select b.sym, b.pricedate, p.price  from  (     select distinct sym, pricedate     from pricetable cross join datestable ) b left join pricetable p on p.sym = b.sym and p.pricedate = b.pricedate order by b.pricedate, b.sym 	0.62113783200868
1544314	31981	a little fuzzy on getting distinct on one column?	select receipts.receiptid,     min(receipts.userid),     min(receipts.usercardid),     min(folderlink.receiptfolderlinkid) from dbo.tbl_receiptfolderlnk as folderlink inner join dbo.tbl_receipt as receipts on folderlink.receiptid = receipts.receiptid group by receipts.receiptid 	0.00473776136548207
1547125	10724	sql - how to find the highest number in a column?	select max(id) from customers; 	0
1560426	37240	how to count number of days?	select table2.id, table2.name, table2.total, sum(datediff(d, dateadd(d, -1, table1.fromdate), table1.todate))     from table1      inner join table2 on table1.id = table2.id     group by table2.id, table2.name, table2.total 	4.76440790426989e-05
1561219	30335	sql looping through results	select id, databaseyouused.dbo.functionyouwrote(id) from databaseyouused.dbo.tablewithids 	0.252378603921266
1566468	2417	sorting nearest date with mysql	select * from tasks order by case when deadline = '0000-00-00'               then '9999/09/09'                else deadline           end asc 	0.122227435088964
1568630	22604	generating random number in each row in oracle query	select t.*, round(dbms_random.value() * 8) + 1 from foo t; 	0.000147779519543029
1575673	23724	mysql limit on a left join	select issues.*,            comments.author as commentauthor,            comments.when_posted as commentposted      from issues left join ( select c1.issue, c1.author, c1.when_posted               from comments c1            join            (select c2.issue, max(c2.when_posted) as max_when_posted                          from comments c2           group by issue) c3             on c1.issue = c3.issue and c1.when_posted = c3.max_when_posted           ) as comments on issues.id=comments.issue  order by coalesce(commentposted, issues.when_opened) desc 	0.743586008520731
1580534	25634	how to know if between 2 date's it past 5 days - oracle 10g?	select case when     abs(to_date('01/05/2009','dd/mm/yyyy') - to_date('06/05/2009','dd/mm/yyyy')) = 5   then 'yes'   else 'no'   end as are_dates_5_days_apart from   dual; 	0
1591019	24790	sql: joining 3 tables, needing to also join the 3rd to itself	select m.uid, m.wp_user_id,m.status,      m.last_login,m.membership_type,      m.membership_expiration,      u.user_login,      f.meta_value first_name,      l.meta_value last_name from mod_membership m    join wp_users u        on u.id = m.wp_user_id    left join wp_usermeta f       on f.user_id = m.wp_user_id          and f.meta_key = 'first_name'    left join wp_usermeta l       on l.user_id = m.wp_user_id          and l.meta_key = 'last_name' 	0.00071430832626177
1593358	9076	mysql & php - query for record with all or fewer values, but not more	select baskets.* from baskets, fruits, baskets_and_fruits where baskets.id = baskets_and_fruits.basketid and     fruits.id = baskets_and_fruits.fruitid and     and baskets.id not in     (         select baskets.id from baskets, fruits, baskets_and_fruits         where baskets.id = baskets_and_fruits.basketid and             fruits.id = baskets_and_fruits.fruitid and             fruits.name not in ('apples', 'oranges', 'grapes')     ) 	0.0147387455420585
1593969	8150	how to run query that contain ( ' ) ? ex: select * from a where b like 'aa'bb'?	select * from a where b like 'aa''bb' 	0.131451686125981
1606605	38860	what's the best way to query for position changes?	select (s0.rank - s1.rank) as change, s1.rank as position, s1.name, s1.score from (select p.name, p.id, sum(g.points) as score, @rank1:=@rank1+1 as rank         from (select @rank1:=0) r, players p       inner join games g on p.id=g.player_id       order by score desc) s1 join      (select p.id, sum(g.points) as score, @rank2:=@rank2+1 as rank         from (select @rank2:=0) r, players p       inner join games g on p.id=g.player_id       where g.id<5       order by score desc) s0 on s0.id = s1.id 	0.239832082625745
1613215	4562	how do i retrieve a random (but unique for a date) primary key value?	select  id from    products order by         rand(unix_timestamp(current_date())) limit 1 	0
1625686	8560	mysql unknown column	select * from ( select   s.name,   s.surname,   s.id_nr,   s.student_nr,   s.createdate,   s.enddate,   (select count(*) from student_attendance where absent = 1) as count_absent  from   student as s,   student_contact as sc,   student_payment as p,   student_courses as scou,   modules as m,   student_certificate as scer,   student_results as sr,   lecturer_profile as l,   lecturer_comments as lc,   student_attendance as sa,   student_training as t  where s.s_id = sc.s_id  and s.s_id = p.s_id  ... and t.s_id = s.s_id  and t.sp_id = 1 ) as x where count_absent = 3 	0.342560400037757
1626583	13990	regexp in a where statement?	select avg(`rating`) from `car_ratings` where `user_car` like '%_56748' 	0.790737631917614
1634150	14583	how can i exclude values from a third query (access)	select t1.* from t1 left join t2 on t1.id = t2.id where t2.id is null; 	0.00226108307758182
1643499	38878	doctrine - filter by foreign agregate value	select  u.name, count(*) as users_phonenumber_count from    users u     inner join phonenumbers p on p.user_id = u.id group by     u.name having     count(*) > 10 	0.0129329719692669
1644110	12355	sql script / table partitioning	select value from v$option where parameter = 'partitioning'; 	0.451816085477646
1662171	29621	sql question : how do i pivot mutiple results to single row?	select    t.name,    d1.delaytime   as delay1,    d1.delayreason as reason1,   d2.delaytime   as delay2,    d2.delayreason as reason2,   d3.delaytime   as delay3,    d3.delayreason as reason3, from train as t left join traindelay as d1 on d1.trainid = t.id  left join traindelay as d2 on d2.trainid = t.id and d2.id > d1.id left join traindelay as d3 on d3.trainid = t.id and d3.id > d2.id 	0.137050885747781
1668297	25009	sql query to get the sum and the latest enries	select id, sum(numofsuccessfiles), sum(totaldata), max(backupsessiontime) from machinestat group by id; 	0.000200573317358168
1669498	7139	are subqueries the only option to reuse variables?	select @one := 1 as one, 2 * @one as two; 	0.0327447971309264
1671765	14320	select all columns for all tables in join + linq join	select new { ctljcrjob, ctlrfdstm } 	0.00245933100380157
1679283	24919	how to write the sql for the following problem?	select * from mytable where col2 in ( select col2 from mytable group by col2 having count(*) > 1 ) x 	0.77555234080083
1689623	30819	create a temporary table like a current table in sql server 2005/2008	select * into #temp_table from current_table_in_stored_procedure #temp_table - locally temp ##temp_table - globally temp select top 0 * into #temp_table from current_table_in_stored_procedure to have empty table 	0.00544902612576093
1692509	34020	how do i retrieve every nth record from a table?	select name from     (select @row:=@row+1 as row, t.name from      tbl t, (select @row := 0) y      where alphabet_index='a' order by alphabet_index) z  where row % 880 = 1; 	0
1722299	38033	return a default row in sql	select a, b, c from foobar  where foo='foo' union all select 'def', 'ault', 'value' from dual  where not exists ( select 'x' from foobar where foo='foo' ) 	0.00839214954825361
1728041	27936	removing duplicates in ms access	select number, count(number) as count from table group by number 	0.620558721194964
1739632	8094	customer and order sql statement	select customername from customer where pk_customerid in ( select fk_customerid from orders inner join customer on customer.pk_customerid=orders.fk_customerid) 	0.116212475626321
1741646	406	how do i do a sql between where the date and time are stored seperatly as integers	select * from transactions where (txndate > @mindate and txndate < @maxdate)    or (txndate = @mindate and txntime >= @mintime)    or (txndate = @maxdate and txntime <= @maxtime) 	0.00164924954807685
1752539	7943	how to get non-group by column x value of the first row of every group by column y of table t?	select   x,   y,   z from (select   x,   y,   min(z) over (partition by y) as z,   row_number() over (partition by y order by x_dt) as rn from t) t2 where rn = 1; 	0
1757984	18637	selecting user with earliest time and joining with other data	select  id,         case when value = 'xyz'              then 'pending'              else 'not pending'         end as status,         time,         first_value(user) over (partition by id order by time) as first_user from    table1 inner join         ... where   subject in (...) and         field = 'status' 	8.12483975056712e-05
1761215	18393	count from a table, but stop counting at a certain number	select * from whatevertable where whatevercriteria limit 100, 1 	0
1773989	15848	sql 2005: how to add same column and fk across multiple tables	select n'alter table ' +quotename(name)+n' add column currentlifecycleid (int) null; alter table '+quotename(name)+n' add constraint fk_lifecycleid     (currentlifecycleid ) references other_table (lifecycleid); ' from sys.tables where name in ('table1', 'table2', ..., 'table73'); 	0.00040453715489392
1777167	12130	select from one table and include sum value from another	select v.link_id, (sum(karma_up) - sum(karma_down)) as points from  links l, votes v where l.link_id = v.link_id group by v.link_id 	0
1791043	10365	query to list the logins and the databases they have access	select db_name(), perm.state_desc, usr.name from sys.database_permissions perm join sys.database_principals usr on perm.grantee_principal_id = usr.principal_id where perm.class_desc = 'database' 	0.00054064812442092
1797811	13447	how to get a list of product categories and their id's from magento?	select entity_id as categoryid, value as categoryname from catalog_category_entity_varchar where attribute_id=111 	0
1797997	9233	value of column in row with previous key	select      upd.id,      upd.views,      (upd.views - coalesce(last_upd.views, 0)) from      updates upd inner join stuff s on      s.id = upd.id and      s.owner = 'someone' inner join updates last_upd on      last_upd.id = upd.id and      last_upd.time < upd.time left outer join updates upd2 on      upd2.id = last_upd.id and      upd2.time < upd.time and      upd2.time > last_upd.time where      upd2.id is null and      upd.time = '01-01-1970 00:00:00' 	0
1800290	38570	number of days between two dates - ansi sql	select extract(day from date('2009-01-01') - date('2009-05-05')) from dual; 	0
1809614	28190	try to find a specific values in a table that can exist in field1 or field2 or field3...(and so on)	select     case '4164553627'      when field1 then 'f1'      when field2 then 'f2'      ...      when field23 then 'f23'      when field24 then 'f24'      when field25 then 'f25' end as field from table 	0.0108721598919767
1810813	17267	count records by group with 0 number for records out of criteria	select     software ,   sum(case when result = 0 then 1 else 0 end) as missing from     test3 group by software 	0
1814144	26122	mysql - is it legal to do 'select table1.*,table2.column from table1,table2'?	select table1.*, table2,columnname from table1     inner join table2         on table1.pkcolumn = table2.fkcolumn 	0.100838586536666
1817985	7215	how do i create a comma-separated list using a sql query?	select    r.name as resname,    a.name as appname from    resouces as r,    applications as a,    applicationsresources as ar where   ar.app_id = a.id    and ar.resource_id = r.id 	0.119655451622716
1818094	12856	how to get affected rows in previous mysql operation?	select * from mytable where column3="a_variable" and status != 2;  update mytable set status=2 where column3="a_variable"; 	0.000596327739499809
1819447	25725	get a list of all functions and procedures in an oracle database	select * from all_objects where object_type in ('function','procedure','package') 	0.00177946497867881
1860457	329	how to count instances of character in sql column	select len(replace(mycolumn, 'n', '')) from ... 	0.00132575155814203
1869753	36222	maximum size for a sql server query? in clause? is there a better approach	select ... from table join (    select x.value(n'.',n'uniqueidentifier') as guid    from @values.nodes(n'/guids/guid') t(x)) as guids  on table.guid = guids.guid; 	0.767508285863249
1877068	34120	a database question for storing and computing with historical data	select m.timestamp, sum(w.widget_count) as counthistory from (     select a.timestamp, b.bin, max(b.timestamp) as intmostrecenttimestamp     from widgettable a         cross join widgettable b     where a.timestamp >= b.timestamp     group by a.timestamp, b.bin, a.widget_count ) m      inner join widgettable w on m.intmostrecenttimestamp = w.timestamp group by m.timestamp order by m.timestamp 	0.426505721128141
1916268	15069	sql set values for some variables with a select	select  @foo = foo,         @bar = bar from    thetable where   id = 37 	0.0350176468119618
1920086	40535	how to create a column of a specific type?	select  company,       city,       dues,       cast(0 as bit) as newcolumn1,       cast(123.12 as real as newcolumn2  from    @table 	0.000766947797902635
1926838	31483	sql select top frequent records	select top(20) [name], count(*) from table where [group] = 1 group by [name] order by count(*) desc 	0.00173702589845027
1942210	23798	which type of join can i use to reproduce these results	select  * from    myview union select  myview.activityrecid,         region.regionrecid,         0 as isexcluded from    myview cross join region where   (myview.regionrecid is not null or myview.isexcluded = 0)         and not exists (             select  null             from    myview             where   myview.regionrecid = region.regionrecid         ) 	0.267620065086647
1944391	40568	getting current system time in sql server	select getdate() 	0.0132969965804269
1945722	37480	selecting between two dates within a datetime field - sql server	select * from tbl where mydate between #date one# and #date two# 	5.51618242480174e-05
1957989	2423	compare 5000 strings with php levenshtein	select similar.id, similar.address, count(*)  from adress similar, word cmp, word src where src.address_id=$target and src.soundex=cmp.soundex and cmp.address_id=similar.id order by count(*) limit $some_value; 	0.296627623531967
1962891	9370	adding fields to optimize mysql queries	select * from tbl_name where col1=val1 and col2=val2; 	0.610391011176167
1984959	20703	mysql return specific row numbers	select xxx from table where xxx_id in (1, 10, 25) order by xxx 	0.000492611524306636
1997519	21402	how do i combine two queries (union all) into one row?	select     sub.gn as groupname,     sum(sub.nj) as normjobs, sum(sun.nc) as normcpu,     sum(sub.sj) as sys7jobs, sum(sub.sc) as sys7cpu   from (       select           groupname as gn,           sum(jobs) as nj, sum(cpu) as nc,           0 as sj, 0 as sc         from tbl           where subsys = 'norm'           group by groupname         union all select             groupname as gn,             0 as nj, 0 as nc,             sum(jobs) as sj, sum(cpu) as sc           from tbl           where subsys = 'sys7'           group by groupname     ) as sub     group by sub.gn     order by 1 	0
2005276	39064	asp.net / sql drop-down list sort order	select  serialnumber,         max(datetimefield) from    table group by serialnumber order by 2 desc 	0.274733466776424
2008853	41104	join two tables based on relationship defined in third table	select activity.activitytext as activity, action.actiontext as applicableaction from activityaction     inner join activity         on activityaction.activityid = activity.activityid     inner join action          on activityaction.actionid = action.actionid 	8.94021930432348e-05
2011584	25200	how to convert this varchar values to a datetime	select krant, cast(cast(jaar as varchar(4))+'-'   +right('0'+cast(maand as varchar(2)),2)+'-'   +right('0'+cast(dag as varchar(2)),2) as datetime) as datum,    inhoud as artikel,    len(inhoud)-len(replace(inhoud,' ','')) as numwords,    'goirle' as vestiging  from [sitecore_bibliotheekmb_krantenknipsel].[dbo].[krangoi] 	0.035817111798899
2026552	32552	query field names of all tables	select * from sys.tables where object_id in (     select object_id from sys.columns where [name] = 'fieldname' ) 	0.000161104858075622
2046591	23700	how to find if a word has all vowels (sql server 2005)	select * from @t  where words like '%a%' and words like '%e%' and words like '%i%' and words like '%o%' and words like '%u%' 	0.00111020400739058
2056558	33025	mysql: substring that returns the first occurance from the right ? (subrstring?!)	select length(`haystack`) - position('needle' in reverse(`haystack`)) 	0.00172583791842213
2057348	26495	in mysql how do i find rows repeating with respect to all fields?	select student, department, count(*) as 'count'  from students group by student, department having count > 1 	4.8312947330346e-05
2069595	4092	parent child table record - building sql query	select     c.cid * d.id as id,     c.code,     case         when c.cid = d.cid then d.name         else null     end as name from code c cross join details d 	0.00366862139439512
2076954	35664	php and multiple db selects	select e.*, c.name as competition_name from events e left join competitions c on c.id = e.competition_id 	0.247469447690298
2083294	3645	determine 'valid until' date in mysql query	select   s1.uid,   s1.spid,   s1.propertyvalue,   s1.creationdate,   min(s2.creationdate) as datetwo from salespointproperty s1 inner join salespointproperty s2     on s1.spid = s2.spid     and s1.creationdate < s2.creationdate group by   s1.uid,   s1.spid,   s1.propertyvalue,   s1.creationdate; 	0.0558229443238381
2093038	6976	order by in sql	select * from table1 orderby column1 asc , column2 desc 	0.410338791385693
2101102	10969	mysql linking tables; some final issues	select f.name, b.value from foo f left join bar b on b.foo_id = f.id where f.age > 10 having b.value is not null 	0.208113431921588
2106372	5930	mysql - select all except what is in this table	select * from image where id not in      (select image_id from user_image where user_id = the_user_id); 	0.270670687151161
2112784	12865	sql server date format issue	select * from orders where convert(varchar(50),orderdate,101) = convert(varchar(50), convert(datetime,'1/21/2010'),101) 	0.766512839540297
2122927	38288	count top 10 inputs in a table	select   count(*) as points,   photoname from likes group by photoname order by points desc limit 10; 	0.000646783916233459
2130749	31194	dynamically create table statement in sql	select * into new_table from table where 1 = 0 	0.270812316375338
2133607	1329	mysql - a select that returns the highest 'views' and a specific id's 'views'	select views from table_1 where row_id = 10 union select max(views) from table_1 	0
2152503	33003	running total for each entry in group by	select count(state)*15 as downtime,application from stats where state='down' group by application 	0
2158811	2335	how to select two record from two different table with one query in mysql	select * from mp3 where baslik like '%$search%' union  select * from haberler where baslik like '%$search%' 	0
2182129	1352	mysql sum in different ways	select    year(history.created_at) as year,   month(history.created_at) as month,   day(history.created_at) as day,   sum(history.value) as total,   sum(case when history.value < 0 then history.value else 0 end) as down,   sum(case when history.value > 0 then history.value else 0 end) as up from `user_raters`  inner join `history_user_raters` as history   on user_raters.id = history.user_rater_id where (user_raters.to_id = 1)   group by date(history.created_at) 	0.0293309865072855
2182697	496	quick sql question! sort by most occurences of an attribute	select c.id, c.name, count(i.id) from categories c left join items i on (c.id=i.categoryid) group by c.id order by count(i.id) 	0.00739803935596842
2188164	15364	is it possible to find the objects which depend on a synonym?	select  * from sys.sql_modules m      inner join sys.objects o on m.object_id=o.object_id where m.definition like '%sfel.elpc%' and type = 'p' 	0.00915394094517833
2207784	11988	show only previous month's data in sql	select top 10 dbo_lu_appname.appname, count(*) as sessionnos from dbo_lu_appname inner join dbo_sdb_session on dbo_lu_appname.pk_appnameid = dbo_sdb_session.fk_appnameid where (((dbo_sdb_session.sessionstart) between now() and dateadd("d",-30,now()))) group by dbo_lu_appname.appname order by count(*) desc; union all select "other" as appname, count(*) as sessionnos  from (dbo_lu_appname inner join dbo_sdb_session   on dbo_lu_appname.pk_appnameid = dbo_sdb_session.fk_appnameid)   left join (select top 10 dbo_lu_appname.appname, count(*) as sessionnos             from dbo_lu_appname            inner join dbo_sdb_session             on dbo_lu_appname.pk_appnameid = dbo_sdb_session.fk_appnameid            where (((dbo_sdb_session.sessionstart) between now() and dateadd("d",-31,now())))            group by dbo_lu_appname.appname            order by count(*) desc) as s  on dbo_lu_appname.appname = s.appname where s.appname is null group by "other"; 	4.82856390439377e-05
2215449	32837	sql query to count total amount of time	select count(distinct _timestamp) from table 	0.000122787953962721
2226824	33846	ordering by the difference between two averages	select `typeid`, avg(if(`bid`, `price`, 0)) as `average_buy_price`, avg(if(`bid`, 0, `price`)) as `average_sell_price`, avg(if(`bid`, `price`, 0)) - avg(if(`bid`, 0, `price`)) as `difference` from `orders` group by `typeid` limit 100 order by `difference` desc; 	0.000288734119367028
2229851	29197	selecting distinct months and years and then breakdown of values for	select count(*), type, year(date_time), month(date_time) from `table`  group by type, year(date_time), month(date_time) 	0
2244173	11596	how can i get a list of indexes where a particular index column appears first?	select     o.name tablename     , c.name columnname     , i.name indexname from     sys.index_columns ic     inner join sys.indexes i on ic.object_id = i.object_id                              and ic.index_id = i.index_id     inner join sys.columns c on ic.object_id = c.object_id                              and ic.column_id = c.column_id     inner join sys.objects o on ic.object_id = o.object_id where     o.is_ms_shipped = 0     and c.name = 'row_company'     and ic.index_column_id = 1 	0
2260909	28124	search query, 'order by' priority	select name, description, content,     priority = case         when name like '%' + @query + '%' then 1         when desription like '%' + @query + '%'  then 2         when content like '%' + @query + '%'  then 3     end case from tbl_content where     name like '%' + @query + '%' or     desription like '%' + @query + '%'  or     content like '%' + @query + '%' order by priority asc 	0.371722541701783
2270799	29349	setting multiple scalar variables from a single row in sql server 2008?	select     @var1 = col1     ,@var2 = col2 from     inserted; 	0.198740646410016
2290725	27403	how can select utc_timestamp() return -10:00 utc?	select  @@system_time_zone, now(), utc_timestamp() 	0.087657339615174
2301647	9403	sql query to sum fields from different tables	select a.id, a.total, b.sb as amountb, c.sc as amountc, d.sd as amountd from a   inner join (select extid, sum(amount) as sb from b group by extid) b on a.id = b.extid   inner join (select extid, sum(amount) as sc from c group by extid) c on c.extid = a.id   inner join (select extid, sum(amount) as sd from d group by extid) d on d.extid = a.id 	0.000948149275401239
2306466	14354	select the number of rows instead of the content in it	select count(distinct(lists.id)) from lists inner join subtitles on subtitles.list_id = lists.id inner join listitems on listitems.subtitle_id = subtitles.id where lists.online = 1 	0
2309943	41282	unioning two tables with different number of columns	select col1, col2, col3, col4, col5 from table1 union select col1, col2, col3, null as col4, null as col5 from table2 	0
2312764	7712	sql query to show difference from the same table	select f.*    from inventory f       left join inventory s         on (f.plate_num = s.plate_num            and s.year_owned = :second-year) where s.plate_num is null    and f.year_owned = :first-year 	0
2318501	34127	how to find sql server queries that took a lot of time?	select top 10     total_worker_time/execution_count as avg_cpu_time         ,execution_count         ,total_elapsed_time/execution_count as avg_run_time         ,(select               substring(text,statement_start_offset/2,(case                                                            when statement_end_offset = -1 then len(convert(nvarchar(max), text)) * 2                                                             else statement_end_offset                                                         end -statement_start_offset)/2                        ) from sys.dm_exec_sql_text(sql_handle)          ) as query_text  from sys.dm_exec_query_stats  order by avg_run_time desc 	0.0554390698402525
2332645	5989	how can i determine a day name in sql server 2005?	select datename(dw,getdate()) 	0.0069324370621615
2334272	822	equally divide resultset into groups, with cursor or not?	select  *,         ntile((select cast(ceiling(count(*) / 6.00) as int) from drivers)) over (order by id) as heat from    drivers 	0.0943418082686616
2348145	32206	ordering mysql results by in sequence?	select x.y, x.z from x where x.id in (23, 55, 44, 12) order by field (x.id, 23, 55, 44, 12) 	0.273687734914936
2363237	9490	sql request with "group by" and "max" and "join"?	select      client.id_client,     sub_query.date_client,     client_attribut.attribut,     client.nom_marital from     client inner join     (select           client_attribut.id_client,           max(client_attribut.date_client) as date_client      from           client_attribut      group by           client_attribut.id_client)      as sub_query on (sub_query.id_client = client.id_client) inner join     client_attribut on (client_attribut.id_client = sub_query.id_client and                         client_attribut.date_client = sub_query.date_client); 	0.637308351132688
2374109	11944	how to use sql to do a group by with different dates?	select    ...,    sum(case when saledate >= dateadd(day, -7, getdate()) then 1 else 0 end) as 7days,    count(*) as 14days from    mytable where    saledate >= dateadd(day, -14, getdate()) group by    ... 	0.0159682630265134
2377169	41219	count of a value in a column in mysql database	select column, count(*) from table group by column 	0.000715573227346765
2381533	30469	php and mysql: optimize database	select fname, lname from employees where ssn = 'blah'; 	0.762736059520942
2395449	11135	table with events unixtime to day statistics	select from_unixtime(unixtime,'%y-%m-%d') as the_date,          count(word) as word_count     from table group by 1; 	0.000247588321256401
2410066	18788	select the same column multiple times	select users.username     , max( case when userstype.usertypeid = 1 then 1 else 0 end ) as type1     , max( case when userstype.usertypeid = 2 then 1 else 0 end ) as type2     , max( case when userstype.usertypeid = 3 then 1 else 0 end ) as type3     , max( case when userstype.usertypeid = 4 then 1 else 0 end ) as type4 from users         join userstype             on userstype.userid = users.userid group by users.username 	0.000267503589266106
2420885	23310	mysql is there a single select to query various unrelated values from a database?	select d.parameter_value,tr.parameter_value  from `maindb`.`tbl_parameter_despatch` as d,tbl_parameter_transactionid as tr ; 	6.87678878361063e-05
2421456	168	sql query to fetch products with most top 1 most recent price change	select     p.id productid     ,p.name     ,coalesce(b.price, p.price) price     ,b.pricechanged from dbo.products as p  left join  (     select       a.productid       ,a.pricechanged       ,pc2.price          from     (         select             pc1.productid            ,max(pc1.pricechanged) as pricechanged         from dbo.pricechanges pc1          group by pc1.productid      ) a              inner join dbo.pricechanges pc2      on (a.pricechanged = pc2.pricechanged and a.productid = pc2.productid) ) b on b.productid = p.id 	0
2424820	5086	t-sql: displaying data from multiple columns into one output column using case and coalesce	select id,      (isnull(southeast,0) + isnull(allregions,0) + isnull(midamerica,0)  + isnull(northcentral,0) + isnull(northeast,0) + isnull(pacificnorthwest,0) + isnull(pacificsouthwest,0)),     affected_area =          case when [allregions]=1 then 'all regions, ' else '' end +          case when [midamerica]=1 then 'mid-america, ' else '' end +          case when [northcentral]=1 then 'north central, ' else '' end +          case when [northeast]=1 then 'northeast, ' else '' end +          case when [pacificnorthwest]=1 then 'pacific northwest, ' else '' end +          case when [pacificsouthwest]=1 then 'pacific southwest, ' else '' end +          case when [southeast]=1 then 'southeast' else '' end  from [db_reporting].[dbo].change c with (nolock) where convert(varchar(10),([needed_by_date]),110) between (dateadd(dd,-7,convert(varchar(10),getdate(),110))) and (dateadd(dd,-1,convert(varchar(10),getdate(),110))) 	0.000874321039893855
2432050	12221	display part of entry	select left(yourcolumn, charindex(' ',yourcolumn)) ... 	0.000218558200750669
2432342	6422	sql server: how to get a subitem of sp_helplanguage?	select * from sys.syslanguages where name='deutsch' 	0.0102047736515227
2432570	35289	finding the number of 1's in my table in order	select cust.id, sum(cone.one) as number_ones  from customers as cust inner join customer_ones as cone on cone.id=cust.id group by cust.id order by number_ones desc 	0.00477375631884637
2440429	19950	mysql query to count unique domains from email address field	select substring_index(email, '@', -1), count(*) from table group by substring_index(email, '@', -1); 	0.000461619879572542
2445878	30576	cassandra api equivalent of "select ... from ... where id in ('...', '...', '...');"	select ... where keyalias in ('key1', 'key2', 'key3', ...); 	0.681976455999083
2462715	13203	how to combine these queries	select * from (     select t.type,t.id,s.title     from db1.tags t     inner join db1.st s on s.id=t.id     where id like '%%' and t.tag='foo' and t.type='s'     order by tag desc     limit 0, 19 ) as t1 union all select * from (     select t.type,t.id,v.title     from db1.tags t     inner join db1.vi v on v.id=t.id     where id like '%%' and t.tag='foo' and t.type='v'     order by tag desc     limit 0, 19 ) as t2 union all select * from (     select t.type,t.id,i.ca as title     from db1.tags t     inner join db2.tablename i on i.id=t.id     where id like '%%' and t.tag='foo' and t.type='i'     order by tag desc     limit 0, 19 ) as t3 order by type, id desc 	0.0999567282871995
2479425	35577	count total number of callers?	select count(distinct 'commenter_name') from 'comment'; 	0.000177199251163232
2483140	20507	oracle: how to "group by" over a range?	select case           when age <= 10 then '1-10'           when age <= 20 then '11-20'           else '21+'         end as age,         count(*) as n from age group by case             when age <= 10 then '1-10'             when age <= 20 then '11-20'             else '21+'           end 	0.0288285757925879
2486725	5285	postgresql join with array type with array elements order, how to implement?	select i.*, idx(id_items, i.id) as idx from some_chosen_data_in_order s join items i on i.id = any(s.id_items) order by idx(id_items, i.id) 	0.192275128741289
2491146	30504	time datatype in sql server 2005	select convert(datetime, '11:22:33') 	0.456088372050998
2492799	36039	sql to list rows if not in another table	select      a.employeeid,     b.employeeid  from      tblemployees a         left join     tblcards b          on             a.employeeid=b.employeeid  where      groupstartdate < '20100301'  and      staffdiscountstartdate > '20100301'  and      datediff(day,groupstartdate,staffdiscountstartdate)>1  and     b.employeeid is null 	0.000540493922609034
2499250	13978	how to display result of subquery rows as one column in mysql?	select moviename,(select group_concat(categoryname) from category b,relcatmov c where b.categoryid=c.categoryid and c.movieid=a.movieid) as categories from movies a; 	0
2501590	35752	is it possible to combine these 3 mysql queries?	select wp.id, wpr.pod_id, wpr.tbl_row_id from wp_pods_rel as wpr join wp_posts as wp   on wp.id = wpr.tbl_row_id where wpr.field_id = '28'   and wp.guid like '%/$downloadfile' 	0.376267228372822
2505728	5858	create table (structure) from existing table	select * into <destinationtablename> from <sourcetablename> where 1 = 2 	0.00226174092492943
2505822	17487	oracle sql: query results from previous x isoweeks () (where x might be > 52)	select         to_char(order_date,'iyyy') as iso_year,        to_char(order_date,'iw') as iso_week,        sum(sale_amount) from orders where order_date >= trunc(sysdate,'iw') - (61 * 7)   and order_date < trunc(sysdate,'iw') group by           to_char(order_date,'iyyy'),          to_char(order_date,'iw') 	0.00645375275780468
2509233	14546	db2: won't allow "null" column?	select     ...    cast(null as int) as column_a,    cast(null as varchar(128)) as column_b,    ... from    ... 	0.764675571491517
2509263	1048	how to get parameter values for dm_exec_sql_text	select *  from sys.dm_exec_requests r  cross apply sys.dm_exec_query_plan(plan_handle) as qp cross apply sys.dm_exec_sql_text(r.sql_handle)  where r.database_id = db_id('<dbname>') 	0.00874762325305669
2533225	30646	mysql count problem	select groups.*, count(users_groups.user_id) as user_count from groups left join users_groups on users_groups.group_id = groups.id group by groups.id 	0.728942343722663
2542935	19725	help with sql query (list strings and count in same query)	select u.userid, username, isnull(x.favoritecount, 0) as favoritecount from user u  left join (select userid, count(*) as favoritecount from registered group by userid) x on u.userid = x.userid 	0.320502509478653
2547610	1652	deceptive mysql query	select *  from mb_posts  where id in (select max(id) from mb_posts group by thread_id) 	0.500458156425026
2548051	19228	sql server 2005 - how to find out what transaction log files have been restored	select distinct r.destination_database_name, r.restore_date,         bs.server_name, m.physical_device_name as backup_device, b.physical_name  from msdb.dbo.restorehistory r       inner join msdb.dbo.backupfile b on r.backup_set_id = b.backup_set_id        inner join msdb.dbo.backupset bs on b.backup_set_id = bs.backup_set_id       inner join msdb.dbo.backupmediafamily m on bs.media_set_id = m.media_set_id 	0.11810982903175
2611174	503	how do i subtract values from two select statements	select v1.value1 - v2.value2 from     (select    max(value) as [value1] from history where datetime ='2010-1-1 10:10' and tagname ='tag1') as v1    cross join   (  (select    max(value) as [value2] from history where datetime ='2010-1-1 10:12'      and tagname ='tag2')  as v2) 	0.00030845745394657
2621586	13622	sql select rows containing part of string	select * from mytable where url = left('mysyte.com/?id=2&region=0&page=1', len(url)) 	0.00214770351471342
2623150	16907	how do i convert an arbitrary list of strings to a sql rowset?	select 'foo' union select 'bar' union select 'baz' 	0.00392960865684843
2630150	6873	converting data in sql server	select convert(datetime, '12-nov-1975') 1975-11-12 00:00:00.000 	0.532620265188196
2631097	7312	mysql group by and count rows problem	select count(*) from   (select x,y       from xx       group by y) sub; 	0.19382450019042
2633235	15336	complex sql query, one to many relationship	select d.dog_id, d.name from dogs as d where d.dog_id = '1'; select c.comment, c.date_added as comment_date_added,        u.username as comment_username, u.user_id as comment_user_id        from comments as c left join users as u on c.user_id = u.user_id        where c.dog_id = '1'; select l.link as link, l.date_added as link_date_added,     u.username as link_username, u.user_id as link_user_id        from links as l left join users as u on l.user_id = u.user_id        where l.dog_id = '1'; 	0.38859689525171
2645776	9101	sql query to select records from three tables seperatly	select     1 as seq,col1, col2, col3, cast(null as varchar (40)) as col4     from table1     where ...  union all  select     2 as seq,'unknown', col2, null, col4     from table2     where ...  union all  select     3 as seq ,col1, col2, col3, cast(null as varchar (40)) as col4      from table3     where ...  order by seq 	0.00134852272651097
2647570	26426	where clause on joined table used for user defined key/value pairs	select userlogin, firstname, lastname from users left outer join  (     select userid     from userpropertyvalues      where propertyvalueid in (@propertyids)     group by userid     having count(userid) =          (             select count(*) from              (             select propertyid from propertyvalues              where id in (@propertyids) group by propertyid             ) p         )    ) filtered on users.userid = filtered.userid 	0.00882180948113286
2657310	2383	mysql - grouping the result based on a mathematical operation and sum() function	select a.type_id, a.type_name, a.no_of_rooms, ( select sum( booked_rooms ) from reservation where room_type = a.type_id and start_date >= '2010-04-12' and end_date <= '2010-04-15' ) as booked_rooms, ( a.no_of_rooms - ( select sum( booked_rooms ) from reservation where room_type = a.type_id and start_date >= '2010-04-12' and end_date <= '2010-04-15' ) ) as freerooms from room_type as a left join reservation as b on a.type_id = b.room_type group by a.type_id order by a.type_id 	0.0288445625148459
2665856	33538	mysql mutliple tables	select pp.id_product from ps_category_product pcp inner join ps_product pp on pp.id_product = pcp.id_product where pp.active = '1' 	0.106489416197454
2667588	37092	find fields with certain characters	select * from domains where ( domain like "%.%.%" ). 	0.000638307073579834
2673053	21412	sql select: "give me all documents where all of the documents procedures are 'work in progress'"	select document_id, document_name, ... from documents as d where not exists (select document_id                   from procedures                   where document_id = d.document_id                       and status != 'wip'); 	0.0266255136005418
2676027	11326	mysql: count two things in one query?	select bool_column, count(bool_column) from your_table  where your_conditions  group by bool_column 	0.012761577228448
2689805	26730	ssas dimension source table changed - how to propagate changes to analysis server?	select ~new column name~ as ~old column name~ from   ~new_table~ 	0.156443894519465
2701043	1388	how to join 1 table twice in the same query and keep results separate	select ..., stylistnotes.note as stylist_note from ... left join notes stylistnotes on bookings.stylistnotes = stylistnotes.notesid 	0.000476541525193366
2713348	37529	mysql: finding rows with conflicting date ranges	select *   from adverts  where `enddate` >= :adstartdate    and `startdate` <= :adenddate 	0.000159061098627567
2723839	26172	mysql: difference of two result sets	select distinct result1.column from result1 left join result2 on result1.column = result2.column where result2.column is null 	0.00160271941063846
2724401	14417	get data from table from a list of strings on mysql	select id, name from tablename where name in ('big','small','extra') 	0
2728999	33454	how to get top 5 records in sqlite?	select * from table_name limit 5; 	0.000125240953970976
2745555	28423	selecting min date excluding 0000-00-00	select  min(mydate) from    mytable where   mydate > '0000-00-00' 	0.00254458642737726
2747178	25704	combining data from two mysql tables	select p.id, p.title, p.post_by, p.content, p.created_at, count(c.comment_id) from posts p left join comments c on p.post_id = c.comment_id group by p.id, p.title, p.post_by, p.content, p.created_at 	0.000926332923628067
2759222	7835	mysql: using of coma separated ids in a table column and group_concat	select a.desc from tablea a inner join tableb b on find_in_set(a.id, b.tableaids) > 0 where b.stock > 1; 	5.42850916128952e-05
2769497	20766	mysql where condition but not limited by it	select   (select sum( value ) from t1 where date = '2010-04-29') as total1,   (select sum( value ) from t2 where date = '2010-04-29') as total2,   (select sum( value ) from t3 where date = '2010-04-29') as total3,   (select sum( value ) from t4 where date = '2010-04-29') as total4 	0.76472875659927
2772153	21930	dont know how to select a few records from a table as utf8	select convert(newvalue using utf8); 	0.00022073187465989
2783347	35215	pl/sql sum by hour	select trunc(stoptime,'hh'), sum(eventcapacity)    from yourtable  group by trunc(stoptime,'hh'); 	0.0289729255747134
2795168	16015	calculate differences between rows while grouping with sql	select       case when source < target then source else target end as source,  case when source < target then target else source end as target,  sum(case when source < target then units else -units end) as diff,      model from  movements group by  case when source < target then source else target end,  case when source < target then target else source end,     model 	0.000335779690460135
2799047	8678	optimal two variable linear regression calculation	select   ((sum(t.year) * sum(t.amount)) - (count(1) * sum(t.year * t.amount))) /   (power(sum(t.year), 2) - count(1) * sum(power(t.year, 2))) as slope,   ((sum( t.year ) * sum( t.year * t.amount )) -   (sum( t.amount ) * sum(power(t.year, 2)))) /   (power(sum(t.year), 2) - count(1) * sum(power(t.year, 2))) as intercept,   ((avg(t.amount * t.year)) - avg(t.amount) * avg(t.year)) /   (stddev( t.amount ) * stddev( t.year )) as correlation from (   select     avg(d.amount) as amount,     y.year as year   from     city c,     station s,     year_ref y,     month_ref m,     daily d   where     c.id = 8590 and     sqrt(       pow( c.latitude - s.latitude, 2 ) +       pow( c.longitude - s.longitude, 2 ) ) < 15 and     s.station_district_id = y.station_district_id and     y.year between 1900 and 2009 and     m.year_ref_id = y.id and     m.category_id = '001' and     m.id = d.month_ref_id and     d.daily_flag_id <> 'm'   group by     y.year ) t 	0.412813766378483
2803747	27329	how to define a current user?	select user() from system.iota; 	0.00177278483974844
2804658	33711	converting output of sql query	select id, case status when 0 then 'unpaid' when 1 then 'paid' else 'unknown' end as status from payments 	0.584237885303488
2804988	6999	mysql get row closest to now()	select name, address, aboutme from users left join     (select aboutme from oldertable     where aboutmeid = users.id     order by datestamp desc     limit 1) where users.id = @userid; 	0.000629273993747812
2805259	15731	mysql query: how to select rows that don't have a certain value?	select distinct group from table where group not in     (select distinct group from table where active = 'yes') 	0
2811742	38772	retrieving multiple rows in sql server but distinct filtering only on one	select        product.name             , max(product.productid) as productid             , max(product.groupid) as groupid             , max(product.gradeid) as gradeid,             , avg(tblreview.grade) as grade from            product left join tblreview on product.groupid = tblreview.groupid where        (product.categoryid = @categoryid) group by product.name having count(distinct product.name) = 1 	0
2813548	30233	how to quote and reference sql server table and field names	select field1 as [first name], field2 as [last name] from [dbo].[tablename] 	0.00330677143602033
2816339	18621	how to change this mysql select into sql server select statement?	select      description =         case when len(description) > 30 then            substring(description,1,30) + '.....'        else            description         end from table 	0.556252717780127
2833578	11341	group by a date, with ordering by date	select b.formattedday, a.*   from sometable a        join         (            select date_format(somedate, '%y-%m-%d') as formattedday,                   min(id) as firstid              from sometable i          group by 1        ) b on (a.id = b.firstid) 	0.0343243414224829
2872788	28218	convert historic dates from utc to local time	select case          when [thedate] between           convert(datetime, convert(varchar(4), year([thedate])) + '-03-' + convert(varchar(2), (31 - (5 * year([thedate])/4 + 4) % 7)) + ' 02:00:00', 20)          and          convert(datetime, convert(varchar(4), year([thedate])) + '-10-' + convert(varchar(2), (31 - (5 * year([thedate])/4 + 1) % 7)) + ' 03:00:00', 20)          then dateadd(hh, 2, [thedate])          else dateadd(hh, 1, [thedate])        end as [thedate],        [thevalue] from   [yourtable] 	0.0108539123271382
2878003	27714	t sql rotate row into columns	select  * from    (          select cpmeasurementguid                ,col + cast(seq as varchar) as colname                ,val          from   (                  select cpmeasurementguid                        ,row_number() over (partition by cpmeasurementguid order by cpprinter_inklevels_id) as seq                        ,cast(inkname as varchar) as ink                        ,cast(inklevel as varchar) as level                  from   [dbo].[cpprinter_inklevels]                 ) as x unpivot ( val for col in ([ink], [level]) ) as unpvt         ) as y pivot ( max(val) for colname in ([ink1], [level1], [ink2], [level2], [ink3], [level3], [ink4], [level4],                                                 [ink5], [level5], [ink6], [level6], [ink7], [level7], [ink8], [level8],                                                 [ink9], [level9], [ink10], [level10]) ) as pvt 	0.00192569516159307
2878432	39362	fetch posts with attachments in a certain category?	select ... from wp_posts as p where exists    (                 select 1                 from wp_posts as p1                     join wp_term_relationship as wtr1                         on wtr1.object_id = p1.id                             and wtr1.term_taxonomy_id in(3)                 where p1.post_parent = p.id                     and p1.post_type = 'attachment'                 )     and p.post_type = 'post' order by p.post_date desc limit 15 	0
2881774	41111	get list of duplicate rows in mysql	select n1.* from table n1 inner join table n2 on n2.vorname=n1.vorname and n2.nachname=n1.nachname where n1.id <> n2.id 	0
2922080	40780	how do i change sql server column names in t-sql?	select 'exec sp_rename ''' + table_name + '.' + quotename(column_name) + ''', ''' + replace(column_name, '%', '') + ''', ''column''; ' from information_schema.columns where column_name like '%[%]%' 	0.0269497021730934
2943346	20157	fastest way to calculate summary of database field	select name,      sum(case              when sign = 'plus' then value              when sign = 'minus' then -value              else 0          end)   from mytable group by name 	0.00116099193853513
2961538	32236	select columns by a concat text as columnname in oracle	select regexp_replace(  regexp_replace( dbms_xmlgen.getxml('  select col'|| to_char(sysdate,'hh24') || ' from table '),'.*<[/]?(\?xml .*>|row).*',''),'  (<([^>]*)>([^<]*)</[^>]*>.*)','\2=\3') as res  from dual 	0.0672983763200706
2962776	23613	using full-text-search in order to find partial words (sql server 2008)	select * from customers where contains(*, '"ann*"') 	0.322789188223615
2998227	36383	mysql- complex data query in a single statement	select * from role where id in (     select role_id     from user_has_role      where user_id = 1     union     select role_id     from user_has_group ug     inner join group_has_role gr on ug.group_id = gr.group_id     where user_id = 1 ) 	0.676369800755116
3002572	21275	top 10 unless count is zero	select top (100) username, fullname_company, fullname, quantity as reffromcount           from         dbo.view_members join (     select reffrom_username, count(*) as quantity     from          dbo.member_ref     where      (refdate >= '5/1/2010') and (refdate <= '6/1/2010')     group by reffrom_username ) as q on q.reffrom_username = dbo.view_members.username where (memberstatus = n'active') and quantity > 0 order by reffromcount desc 	0.00884021003342948
3005361	34387	how to query on table returned by stored procedure within a procedure	select  * from    openrowset ('sqloledb','server=(local);trusted_connection=yes;','set fmtonly off exec master.dbo.sp_who') as tbl 	0.155949371311894
3011960	3477	how to list all duplicated rows which may include null columns?	select a, b from (     select a, b,         count(*) over (partition by a, b) cnt     from dbo.t ) theresult where cnt > 1 	0
3017159	14866	mysql - limit a left join to the first date-time that occurs?	select task_a, dts_completed, bb.started from tablea inner join  (select task_b, min(dts_started) as started from tableb group by taks_b)bb on (bb.task_b = tablea.task_a and bb.started > tablea.dts_completed) 	0.0021903999421684
3027832	37258	drop all stored procedures in mysql or using temporary stored procedures	select     concat('drop ',routine_type,' `',routine_schema,'`.`',routine_name,'`;') as stmt from information_schema.routines; 	0.538008371809044
3040147	14834	how can i pull data from a sql database that spans an academic year?	select     count(*) as [count],     year(my_date) as [year],     month(my_date) as [month] from     downloads where     my_date >= '2009-08-01' and     my_date < '2010-06-01' group by     year(my_date),     month(my_date) order by     year(my_date), month(my_date) 	0.000117549810140661
3046847	21639	counting the instances of customers	select customerid, count(*) as numberofoccurences     from tablex group by customerid; 	0.000217992381820399
3054592	2876	mysql query that can pull the data i am seeking?	select a.instanceid, b.field1, d.field4 from instances as a      join table1 as b on a.instanceid = b.instanceid     left join table2 as c on b.reference_field2 = c.instanceid     left join table3 as d on (c.instanceid = d.instanceid and c.field3 = d.fieldid) where a.active = 'y' 	0.550858506850703
3057143	14296	sql query to get field value distribution	select subject_id     , sum( case when score = 0 then 1 else 0 end ) as [0]     , sum( case when score = 1 then 1 else 0 end ) as [1]     , sum( case when score = 2 then 1 else 0 end ) as [2]     , sum( case when score = 3 then 1 else 0 end ) as [3]     , sum( case when score = 4 then 1 else 0 end ) as [4] from table group by subject_id 	0.00174915046524363
3064121	33314	mysql: how do i combine a stored procedure with another function?	select mywithin( pointfromtext( concat( 'point(', latitude, ' ', longitude, ')' ) ) , polyfromtext( 'polygon(( 0 0, 0 10, 10 10, 10 0, 0 0))' ) )as result, latitude, longitude from mytable 	0.266931427770788
3066844	12515	sql for selecting only the last item from a versioned table	select distinct on (parent_id)      parent_id   , version_id from items order by parent_id, version_id desc 	0
3070980	1444	sql server: looking for table usage through out database	select so.name, so.xtype from sysobjects so (nolock) inner join syscomments sc (nolock) on sc.id = so.id where sc.text like '%tablename%' 	0.460007479513864
3071033	8860	compare two string with mysql	select * from mytable order by abs(ascii(substring(zip_code,1,1)) - ascii(substring('aaaaa',1,1))) asc,          abs(ascii(substring(zip_code,2,1)) - ascii(substring('aaaaa',2,1))) asc,          abs(ascii(substring(zip_code,3,1)) - ascii(substring('aaaaa',3,1))) asc,          abs(ascii(substring(zip_code,4,1)) - ascii(substring('aaaaa',4,1))) asc,          abs(ascii(substring(zip_code,5,1)) - ascii(substring('aaaaa',5,1))) asc 	0.0100469158769993
3076220	29039	how to reverse a field in sql server 2008	select reverse('abcdef') fedcba (1 row(s) affected) 	0.216795725269514
3078312	12605	msql table name with $ sign	select symbol, open, high, low, close, vol, ev from "$aapl" 	0.149617877075854
3087388	5733	how to select only one full row per group in a "group by" query?	select id,b,c from tablename  inner join ( select id, count(a) as countduplicates from tablename as base group by a,id having (count(a) > 1)  )d on tablename.id= d.id 	6.07333049049383e-05
3102967	5929	random() in mysql?	select * from x where flags = 0 order by rand() limit 1 	0.13235804066903
3118469	39718	sql query to find rows that aren't present in other tables	select third.* from third left join first on third.otherid = first.id left join second on third.otherid = second.id where first.id is null and second.id is null 	0
3121587	16923	sql query with 2 foreign keys from one table	select  p.id,         u1.name ownername,         u2.name clientname from    projects p         left join                 users u1                 on p.owner = u1.id         left join                 users u2                 on p.client = u2.id 	5.34803164838432e-05
3127541	7788	sql select null and non null values in where clause	select   student.id, student.student, language.language from   student left join language       on student.languageid = language.languageid 	0.288367530982136
3165999	21752	sql ordering by date but maintain foreign key groupings	select i.*    from item i        left join item_parent p            on p.id = i.parentid    order by         (select max(date) from items         where isnull(parentid,0) = isnull(i.parentid, 0)) desc,          i.parentid, i.date desc 	0.0168482461031669
3171753	38654	mysql: list of rows in table that aren't referenced in another	select tt.*      from timetable tt      join day_name dn on dn.day_name_id = ttt.day_name_id                      and dn.day_name = date_format('2010-7-5', '%w'); left join lesson_booking lb on lb.timetable_id = tt.timetable_id                            and lb.booking_date = '2010-07-05'     where lb.lesson_booking_id is null 	0
3188056	36091	having a generated column depend on other generated columns	select foo,   case when foo='blah'   then 'fizz'   else 'buzz'   end as bar from ( select 'blah' as foo ) a 	0.000659488086919332
3204669	24374	check that the values in all the columns are different in sql - oracle	select * from  (select sys.dbms_debug_vc2coll(1,2,3) a,           sys.dbms_debug_vc2coll(1,2,3) multiset union distinct sys.dbms_debug_vc2coll() b  from dual) where a=b; select * from  (select sys.dbms_debug_vc2coll(1,2,3,1) a,           sys.dbms_debug_vc2coll(1,2,3,1) multiset union distinct sys.dbms_debug_vc2coll() b  from dual) where a=b 	0
3210443	21958	fetching fetch the first occurrence from the result	select      distinct       tab1.col1,      tab2.col1,      min(tab3.col1) from       table1 tab1       join table2 tab2 on tab1.col1 = tab2.col1      join table3 tab3 on tab1.col1 = tab3.col1  group by tab1.col1, tab2.col1 	0
3231105	37323	merge two (or more) arrays and keep values that are highest?	select max(perm1), max(perm2), max(perm3), max(perm4), max(perm5), max(perm6), max(perm7) from group_perm_linking_table where group in ('gr1', 'gr2', 'gr3', 'gr4') 	0
3235471	256	count on the same table	select title,  (select count(*) from tags where title=t.title) as count from tags t  where page_id=42  order by count desc, title collate nocase asc; 	0.00124347546728292
3245532	8388	mysql: list of sum for several conditions in one sql statement	select sum(x) as "sum", date as "date" from (    select distinct a.id as id, a.dur as x, date(from_unixtime(rtime)) as date from b_c        inner join c on b_c.c_id = c.id        inner join a on c.id = a.c_id        inner join a_au on a.id = a_aud.id        inner join d on a_au.rev = d.rev        where           b_c.b_id = 30 and           a_au.stat != 1 ) as subselecttable group by date; 	0.00427769281537017
3254697	21668	mysql - how to check if user_id or friend_id are equal to the logged in users id?	select count(id) as num  from users_friends  where (     user_id = '$sanitized_user_id'      or friend_id = '$sanitized_user_id'   )   and friendship_status = '1' 	0
3258105	29435	tsql - max or top date on an unnormalized table	select userid, user, max(userupdate) as maxdate from mytable group by userid, user 	0.018000946904027
3269273	14123	sql where id = total ids	select *      from table      where id > (select max( id ) from table) - 50            and whatimlookingfor = 'somesuch' 	0.000111054067759073
3269857	35094	mysql - check if a string contains numbers	select * from table where tag regexp '[0-9]' 	0.0030208724327259
3278970	35121	searching technique in sql (like,contain)	select * from test where 'xxxxxx_ramakrishnan_zzzzz' like '%' + name + '%'; 	0.53184178567271
3281450	1436	how to display all the types that i've created using "create type" in postgresql?	select   t.oid                                   ,          t.*                                     ,          format_type(t.oid, null)    as alias    ,          pg_get_userbyid(t.typowner) as typeowner,          e.typname                   as element  ,          description                             ,          ct.oid as taboid from     pg_type t          left outer join pg_type e          on e.oid     =t.typelem          left outer join pg_class ct        on ct.oid    =t.typrelid and      ct.relkind <> 'c'          left outer join pg_description des on des.objoid=t.oid where    t.typtype                                      != 'd' and      t.typname                                not like e'\\_%' and      t.typnamespace                                  = 3278632::oid and      ct.oid                                    is null order by t.typname 	0.000127712432480272
3289503	18352	sql query to count records	select name, count(*) from entrylog where checkin group by name 	0.0394504123442869
3293939	6277	how do i create a join which says a field is not equal to x?	select p.person_id, p.gender, p.name, disease_id      from person_t p       join disease_t d on d.person_id = p.person_id  left join drug_t dt on dt.person_id = p.person_id                    and dt.drug_id = 34     where disease_id = 52       and dt.person_id is null 	0.0365475548414254
3332774	25626	sql retrieve yearly repeated event	select     * from     event where     month([date]) = 12 and     day([date]) = 25 	0.00644288926389679
3336868	39481	how to check if a type of row exists in a table	select * from orders o left join payment p1 on o.order_num = p1.order_num left join payment p2 on o.order_num = p2.order_num where p1.type = "a" and p2.type = "b" and p1.amount = p2.amount 	0.000196870333953938
3343857	7167	php/sql: using only one query, select rows from two tables if data is in both tables, or just select from one table if not	select  ratings_stats.votes,          ratings_stats.total_value,         ratings_stats.view,          ratings_stats.fav,          ratings_stats.wish,         ratings_external.votes,          ratings_external.total_value from  ratings_external left join ratings_stats on ratings_stats.imdbid = ratings_external.imdbid where ratings_external.imdbid = ? limit 1 	0
3346385	13430	datetime pattern for yyyy.mm.dd.hh.mm.ss pattern code?	select     cast(year(my_date) as char(4)) + '.' +     right('0' + cast(month(my_date) as varchar(2)), 2) + '.' +     right('0' + cast(day(my_date) as varchar(2)), 2) + '.' +     right('0' + cast(datepart(hour, my_date) as varchar(2)), 2) + '.' +     right('0' + cast(datepart(minute, my_date) as varchar(2)), 2) + '.' +     right('0' + cast(datepart(second, my_date) as varchar(2)), 2) 	0.337520803124606
3358387	11133	merging result from 2 columns with same name and not over-writing one	select *,cc.configuration as cc_conf, ci.configuration as ci_conf from `content_category` cc , `content_item` ci where ci.content_id = '" . (int)$contentid . "' and ci.category_id = cc.category_id and ci.active  = 1 	0
3387549	10528	checking the existence of one record in multiple rows	select c.*      from content as c left join content_territory as ct        on c.id = ct.content_id     where ct.id in ( ... )  group by c.id 	0
3391746	20931	mysql query incorporation both join tables and nested sets	select node_id, group_concat(name separator ' ') from taggings inner join tags on taggings.tag_id=tags.id inner join (select node.id as node_id, parent.id as parent_id from categories as node, categories as parent where node.lft between parent.lft and parent.rgt) subcategories on subcategories.parent_id=taggings.taggable_id group by (node_id); 	0.629870068806371
3424770	17801	check whether the data is already exist in table, or to check table is empty	select count(*) from `tablename`; 	0
3433246	25154	how to convert a date format	select t.id,             datediff(str_to_date(t.carddate, '%m/%d/%y'), curdate)    from table t 	0.0156015207073848
3447577	26766	selecting all values from row based on one distinct column	select     a1.* from     [tablename] a1     inner join      (         select             a.city             ,   a.price             ,   min(a.depdate) as depdatemin         from             [tablename] a             inner join             (   select                     city                     ,   min(price) as pricemin                 from                     [tablename]                 group by city             ) b on a.city = b.city and a.price = b.pricemin         group by              a.city, a.price     ) b1 on a1.city = b1.city and a1.price = b1.pricemin and a1.depdate = b2.depdatemin 	0
3448544	11417	find missing values in mysql	select     * from     courses c where     c.id not in (     select         ec.course_id     from         enrolled_courses ec     where         ec.user_id = 1 and ec.course_id is not null     ) 	0.0121960991063378
3456664	5857	repeat break columns in a single query group report oracle	select employee_id, first_name, last_name,        job_id, salary, department_id,         department_id as department_id2  from employees  order by department_id, employee_id 	0.0106759577831699
3462799	507	how to view transaction logs?	select * from  fn_dblog(null, null) 	0.218259402542793
3463452	35789	using generated column in a mysql where clause	select column1, (     select count(*) from table2 ) as some_count from table1 having some_count > 0 	0.531983741419411
3464055	26562	4 queries on the same table, a better way?	select sum(club) as club,         sum(case when substr(code, 1, 1) = '9' then 1 else 0 end) as 5pts,        sum(case when substr(code, 1, 1) = 'a' then 1 else 0 end) as 10pts,        sum(case when substr(code, 1, 1) not in('9', 'a') then 1 else 0 end) as general   from action_6_members; 	0.00908452083520174
3465304	39392	finding duplicate rows but skip the last result?	select ...        row_number() over (partition by email order by emailid desc) as rn from ... 	0
3474870	32228	how can i sort a 'version number' column generically using a sql server query	select versionno from versions order by cast('/' + replace(versionno , '.', '/') + '/' as hierarchyid); 	0.0240364141882478
3475759	30375	mysql select replace - use manual values instead of joined lookup table	select  u.name, c1.value, c2.value from    dbo.users u         inner join (           select 'c1_1' as code1, 'interested' as value           union all select 'c1_2', 'maybe'           union all select 'c1_3', 'not interested'         ) c1 on c1.code1 = u.code1         inner join (           select 'c2_1' as code1, 'prepared' as value           union all select 'c2_2', 'self-study'           union all select 'c2_3', 'novice'         ) c2 on c2.code1 = u.code2 	0.00899108380772406
3484184	35582	setting a value by assuming column in a table mysql/php	select case when `1`+`2`+`3`+`4`+`5`+`6`+`7`+`8` < 4 then 'failed' else 'passed' end from test_table; 	0.0254173029597909
3503742	689	how to get date representing the first day of a month?	select dateadd(m,datediff(m,0,getdate()),0) 	0
3525396	4877	best way to write union query when dealing with null and empty string values	select       nullif(column1, '') as [column1],     nullif(column2, '') as [column2] from tablea union select      nullif(column1, '') as [column1],     nullif(column2, '') as [column2] from tableb 	0.756019598718654
3544047	8179	sql highscores	select u.user,          sum(s.runtime) as total_run_time,          sum(s.monsterskilled) as total_monsters_killed,          sum(s.profit) as total_profit,          sum(s.tasks) as total_tasks,           sum(s.xpgain) as total_xp_gained     from users u     join session s on s.userid = u.userid group by u.user order by total_run_time desc 	0.469996064860936
3545660	17019	how do i join a third table in my sql statement which returns a count without losing the 0 count items?	select t.teamid,           t.teamname,            (select count(*) from players inner join medicaltests on players.playerid = medicaltests.playerid where players.teamid = t.teamid and medicaltests.passedmedical = 1) as playercount,           t.rosterspots      from teams t  group by t.teamid, t.teamname, t.rosterspots 	0.00714848335278987
3576304	13491	mysql row number	select x.id, x.name, x.surname, x.rownum  from (       select @rownum:=@rownum+1 rownum, t.*       from (select @rownum:=0) r, employees t       order by id  ) x  where x.name = 'john'   and x.surname = 'banjo' 	0.00468824594640052
3584156	11561	how to sql join two tables so that all entries of the left one are in the result even if there is no matching entry in the right one?	select p.*, r.*  from product p left join review r    on r.product_id = p.id and r.user_id=:userid 	0
3585925	28583	mysql: avoiding cartesian product of repeating records when self-joining	select a_numbered.id, a_numbered.identifier, b_numbered.id from  ( select a.*,        case            when @identifier = a.identifier then @rownum := @rownum + 1           else @rownum := 1        end as rn,        @identifier := a.identifier   from a   join (select @rownum := 0, @identifier := null) r order by a.identifier ) a_numbered join ( select b.*,        case            when @identifier = b.identifier then @rownum := @rownum + 1           else @rownum := 1        end as rn,        @identifier := b.identifier   from b   join (select @rownum := 0, @identifier := null) r order by b.identifier ) b_numbered  on a_numbered.rn=b_numbered.rn and a_numbered.identifier=b_numbered.identifier 	0.0394605874963541
3586302	34138	mysql rows to columns, text type	select max(case when t.option_name = 'option1' then t.option_value end) as option1,          max(case when t.option_name = 'option2' then t.option_value end) as option2     from table t    where t.option_name in ('option1', 'option2') group by t.component_id, t.option_parent 	0.00355513390737486
3594744	6209	mysql, sorting before a group by	select c1, c2, c3  from (select c1, c2, c3 from table order by c2 desc) t  group by c1; 	0.182430047058335
3597078	15024	unique pair in a "friendship" database	select id_low as friend from tbl_friends where (id_high = ?) union all select id_high as friend from tbl_friends where (id_low = ?) 	0.027667597370283
3598451	9901	how to return time from if-clause	select time(start_time) as start,     time(end_time) as end,     time_to_sec(timediff(end_time, start_time)) as durationsecs,     if(         timediff(end_time, start_time) >= "06:00:00",         timediff(end_time - interval 30 minute, start_time),         timediff(end_time, start_time)     ) as duration from [...] 	0.00316348829665135
3605195	17306	mysql - mapping user username to user's id in a query	select m.m_id, u.username, m.message from messages m, users u where m. auhor_id = u.m_id; 	0.00518162081621679
3616802	39378	how to select oldest date in sql?	select top (5) partnumber,serialnumber,min(wip_completiondate) as dates from dbo.fg_fillin where status='fg-fresh' and wip_status<>'cmpl01' and partnumber='p02-070161-10211-c100' group by partnumber,wip_completiondate,serialnumber order by dates 	0.0127662003680038
3625812	20869	get number of connected users in sql server 2000	select spid, status, loginame,  hostname, blocked, db_name(dbid) as databasename, cmd  from master..sysprocesses where db_name(dbid) like '%<database_name>%' and spid > 50 	0.000743961315995477
3632366	37329	oracle select : count of events per team and per year	select  team.team_id,  years.year,  coalesce(count(event.event_id),0) events from  team    join (select distinct extract(year from start_date_time) year from event) years on 1=1    left outer join event on event.team_id = team.team_id and extract(year from event.start_date_time) = years.year group by  years.year,  team_id order by  year  asc,  team_id  asc ; 	0
3633577	21335	how to get max value from more than one table	select max(sessionno)  from       (       select sessionno      from table1      union all      select sessionno      from table2      union all      select sessionno      from table3   ) 	0
3660377	4507	ms access import table from file in a query	select * into newtable from [text;hdr=yes;fmt=delimited;database=c:\docs].test.csv 	0.0576708938897375
3683890	40153	oracle: enumerate groups of similar rows	select id, x, sum(new_group) over (order by id) as group_no from ( select id, x, case when x-prev_x = 1 then 0 else 1 end new_group   from   ( select id, x, lag(x) over (order by id) prev_x     from mytable   ) ); 	0.00328274343856989
3684210	38410	sql query count the zeros	select v.country, sum(v.zero2nine) as [0-9], sum(v.ten2nineteen) as [10-19] ...  from  (   select country,    (case when age between 0 and 9 then 1 else 0 end) as zero2nine,    (case when age between 10 and 19 then 1 else 0 end) as ten2nineteen    from ...   )  as v  group by  v.country 	0.082160600766933
3698954	1417	how to check if format is correct	select case when ( charindex('-',columnname) > 0 and isnumeric(left(columnname,(charindex('-',columnname)-1))) > 0 and  isnumeric(right(columnname,(charindex('-',columnname)))) > 0 ) then 1 else 0 end as properword  from mytable 	0.178464899579659
3705238	31203	how do i get like and count to return the number of rows less than a value not in the row?	select count(id) from my_table where id < (select id from my_table   where substring(id, 2) >= 4 order by id limit 1) 	0
3709229	21732	left join return null even if there are no rows	select cat.id, cat.name   from user left join cat on cat.id = user.catid  where user.id = 2 	0.0290185424391138
3711016	638	sql query: sum on three columns with criteria	select sum(p.amount * (p.percentage/100)) as totalproj,         entities.idx as idx,         count(p.idx) as numproj,         entities.name  from  ( select idx, amount, usercol1 as usercol, percentage1 as percentage from projects union all select idx, amount, usercol2 as usercol, percentage2 as percentage from projects union all select idx, amount, usercol3 as usercol, percentage3 as percentage from projects ) p  inner join entities on p.usercol=entities.idx   where p.usercol=entities.idx   group by name   order by totalproj desc 	0.0118989751994249
3714295	14230	how to reset the 'role settings' in sql server 2008?	select     'revoke deny ' + name + 'stuff' from     sys.server_principals ... 	0.27677365733976
3718545	34240	get friends data in mysql	select     members.id as userid,      members.gebruikersnaam as username,      members.pasfoto as avatar,     members.id as link,  from members join (     select friends.friend_out as member_id      from friends     where friends.friend_in = '123'     and friends.active = 1      union     select friends.friend_in as member_id      from friends     where friends.friend_out = '123'     and friends.active = 1  ) t1 on members.id = t1.member_id order by members.username 	0.00226711373679447
3721877	12674	how to get the month from a string in sql?	select datepart(mm, cast('feb2008' as datetime)) 	0
3757670	40586	sql server year	select convert(varchar,year(getdate())-2) + ', ' +  convert(varchar,year(getdate())-1) + ', ' +  convert(varchar,year(getdate())) 	0.0764294530910064
3758145	29483	mysql sort by 2 parameters	select * from table where pd_sort <> 0 order by pd_sort union select * from table where pd_sort = 0 order by pd_code 	0.101260607299458
3760956	31232	how do i write a sql query for a specific date range and date time using sql server 2008?	select *   from mytable  where cast(readdate as datetime) + readtime between '2010-09-16 5:00pm' and '2010-09-21 9:00am' 	0.00478622138784093
3766986	17150	pivot table: getting data from one column	select date as date, sum( if(  status =  'accept', 1, 0 ) ) as accept, sum( if(  status =  'reject', 1, 0 ) ) as reject from pivot group by date 	0.000320973083190948
3771546	36429	mysql 3 table join	select ls.title, ls.id, ls.url, ls.description from listings ls where  ls.id in (    select lm.listing_id    from location_map lm    where lm.location_id = 123 ) 	0.152506323835361
3793319	20929	efficient sql query to sum unsettled trades by date	select alldates.date, sum(trades.amount) from alldates join trades     on trades.tradedate<=alldates.date     and trades.settlementdate>alldates.date group by alldates.date 	0.213325020759334
3796261	15129	determining the number of occurrences of a record	select s.sid   from student s  where exists(select null                  from interview i                 where i.sid = s.sid             group by i.sid               having count(*) > 5)    and not exists(select null                      from interview i                    where i.sid = s.sid                      and i.outcome = 'offer') 	0
3802324	23678	how to select unique rows only in sql?	select senderuserid, max(receiveruserid) from messages group by senderuserid 	0.000305346664999032
3808086	8290	drop tables by date it were created	select      'drop table  [' + s.name +'].[' + t.name +']' , t.create_date  from      sys.tables t inner join     sys.schemas s     on     s.schema_id = t.schema_id where      create_date< dateadd(year,-3, getdate())      and type='u' 	0.00700374484948497
3823296	5406	mysql datetime related queries: how to calculate the expired entry?	select * from my_tb where timestamp + interval maxdays day < current_timestamp; 	7.93097196651792e-05
3823474	30768	ms sql server 2005 group by and sum	select sum(total) as total, hrcode  from   tblwo as wo,           tblwod as wod,           tblwa as wa    where wod.orderid = wo.id    and wa.hrcode  = wo.administratorcode    and wo.orderdate between '2010-01-01' and '2010-08-31'    and approved = '1'    group by hrcode 	0.740794093234111
3832212	18126	find the minimum flow in a day and the time it occurs	select d1.data_point_groupid      , min(d1.timeid) [timeid]      , min(d1.[value]) [value]  from dma.dbo.calculated_average_group_flow d1 where night=1 and 1e-9 >= (     select abs(d1.value - min(d2.value))      from dma.dbo.calculated_average_group_flow d2      where night=1         and d2.[date]=d1.[date]         and d2.data_point_groupid=d1.data_point_groupid ) group by d1.data_point_groupid, d1.date 	0
3836413	32369	retrieving weekend data rows only in oracle	select *     from yourtable     where  to_char (created_date, 'dy') in ('sat', 'sun') 	0.000346117306254572
3838373	34435	how to identify sql server instances installed on local machine?	select @@version 	0.598468119319334
3842863	41020	select row matching a condition if no other rows match a different condition	select name from table t1 where activity_status != 'active' and not exists (select *         from table t2         where             t2.activity_status = 'active' and t1.name = t2.name) 	0
3844008	29877	how to get hour from subtract date and time in mysql?	select ( unix_timestamp( "2010-12-04 17:07:14" ) -       unix_timestamp("2010-05-30 17:07:19" ) ) / 3600 	0
3853035	7980	mysql - how many people are not in a joined table?	select agents.agentid, agents.firstname, agents.lastname   from agents  where agentid not in        (select agents.agentid           from agents           left join schedule using (agentid)           left join projects using (projectid)          where (projects.locationid = 51)        )  order by agentid; 	0.00162064068958547
3858081	11518	average time from datetime dataset in sql server 2005	select name, reference1,     convert(varchar,  cast(avg(cast(completedtime as float) - cast(completedtime as int)) as datetime),108) averagetime         from tblorderroutestops         where name not like 'cta%' and reference1 <> '000000' and name <> '' and completedtime is not null         group by name, reference1 	0.00105177737256579
3870983	15302	get data form 'dictionary' table	select a.id, a.name, b.explaination  from a inner join b on a.secret_key = b.secret_key 	0.00283664201695168
3877518	14394	query to find all fk constraints and their delete rules (sql server)	select name, delete_referential_action_desc from sys.foreign_keys 	0.000225316343781537
3880692	33186	mysql find data in one table based on one of two fields in another table	select members_table.*, joined_tables.*  from members_table,  ((select * from second_table   join members_table      on members_table.email_address = second_table.email_address) union (select * from second_table   join members_table      on members_table.telephone_number = second_table.telephone_number) ) joined_tables; 	0
3885644	32870	how can i explore the data in a sql database, including foreign tables?	select * from finaltable where id in      (select id2 for table2 where anotheridcolumn in      (select id3 from yetanothertable where yet anotheridcolumn in (input_id_you're_looking_for) 	0.000423916135846206
3892027	25433	select that finds if multiple	select    maintable.name  from maintable m inner join assn_main a on m.appid = a.appid  where    exists (select appid           from assn_main           where appid = m.appid           group by appid            having count(*)>1); 	0.026559018125797
3912126	30419	query on sql mysql 5.1 - find phone numbers with specific area code	select * from table where cellno like '256%' 	0.0748150998772961
3923982	31696	how to combine these two sqls into one?	select     sum(case when d_entered>(current_timestamp-2 hours) then 1 else 0 end as newercount     ,sum(case when d_entered<=(current_timestamp-2 hours) then 1 else 0 end as oldercount     from trans_calc      where i_tracking_code = 112 	0.00150005753232049
3925578	38276	oracle quartz selectwithlocksql value?	select * from <table_name> where <condition> for update; 	0.101102433905041
3939156	27578	distinct question	select min(firstname), lastname from ... group by lastname 	0.664382091071601
3939260	5602	mysql stored procedures - returning message	select "procedure completed" as "result"; 	0.769637008614892
3942353	12110	mysql: search range of strings with slash	select substring_index(fieldname,'/',-1) as v from tablename where v between 1 and 5 	0.0850401374375028
3962639	10176	how to get average tax rates with sql from a one-to-many relationship	select s.name,avg(b.bracket) as averagetax from states s inner join brackets b  on s.numerickey=b.numerickey group by s.id,s.name,b.bracket 	0.000411213346108298
3978939	20969	convert timestamp to a readable date during query	select   from_unixtime(timestamp_field) as formatted_date from   tablename; 	0.0255773645230447
4017603	34280	sql duplicate data for excel dynamic table	select distinct f.*,        f.rmumsr as de,        coalesce((select umconf from umconv where umresr = f.recurv and umfr = f.rmumsr and umto = 'pz'), 1) as piezas,        coalesce((select umconf from umconv where umresr = f.recurv and umfr = f.rmumsr and umto = 'pl'), 1) as palet,        coalesce((select umconf from umconv where umresr = f.recurv and umfr = f.rmumsr and umto = 'cj'), 1) as cajas from fa960 f 	0.0567652320781888
4023160	34919	prevent inserting overlapping date ranges using a sql trigger	select *   from testdatetrigger t    join inserted i    on ((i.validto >= t.validfrom) and (i.validfrom <= t.validto))   where not (i.validto=t.validto and i.validfrom=t.validfrom) 	0.00360689971454245
4036244	4114	sql select query name -value pair	select   id from table where   (name = 'home' and value = 'montreal')   or   (name = 'visitor' and value = 'montreal') 	0.0180712705372329
4040991	33263	how can i aggrategate/pivot this data?	select et1.system_id, et1.[date] as datedown, et2.[date] as dateup, datediff(s, et1.[date], et2.[date]) as downforseconds     from eventtable et1     left join eventtable et2 on et1.system_id = et2.system_id and et2.[event] = 'up' where  et1.[event] = 'down' and et2.[date] = (select top 1 [date] from eventtable where system_id = et2.system_id and [date] > et1.[date]) 	0.614037007491676
4059983	6610	conditional count of related records	select c.customer_id, title, surname, forenames, count(booking_id) as bookings from customer c  left join booking b  on (c.customer_id = b.customer_id and b.booking_live = true) where customer_live group by c.customer_id, surname, forenames, title order by surname; 	0.00521133474638324
4064395	30846	can i combine these 2 simple queries into one query?	select type, count(distinct id) as cnt from svn where name = 'ant' and type in ('feature', 'bug') group by type 	0.0455444182657692
4081815	2345	php calculate starttime and end time from a list of mintues with id's	select      time_id,      min(time_duration) as start_time,      max(time_duration) as end_time from      abc_table  group by      time_id; 	0
4087456	26606	drop all tables from sql ce database	select 'drop table ' || table_name || ';'   from information_schema.tables; 	0.00734860229112977
4095459	32558	mysql: foreign keys	select * from invoice_payments inv left join invoice_cc_gateway gw on inv.paymentid = gw.paymentid where paymenttype = 1 union select * from invoice_payments where paymenttype = 0 	0.0111415547675898
4097266	986	basic sql : selecting the same column multiple times in one query, when each occurrence is dependent on different where clause	select (select x from table where y=1) as x1, (select x from table where y=2) as x2, (select x from table where y=3) as x3 	0
4097499	164	get specific count for character from a column without using a function or stored proc	select len(mycolumn) - len(replace(mycolumn, ';', '')) from sampletable where ... 	0.0210527891796467
4113384	6106	is there a way to combine a sql column with a like	select * from table where column_a like concat('%',column_b,'%') 	0.232593326635231
4123418	5859	how to find rows that have a value that contains a lowercase letter	select * from my_table  where upper(some_field) != some_field 	0
4131937	38899	mysql count unique row values	select count(distinct clientid) from quotation 	0.000616062691758828
4135228	38462	t-sql update 1 to 1000 column	select ... into ... from ... 	0.0437473982110715
4136447	19250	selecting from a table where the name is passed as a variable	select @sqlstring = 'select @numrowsout = count(*) from ' + quotename(@tablename) execute sp_executesql .... 	0.000880179333463233
4153566	20303	get intime and outtime from the table of a day and particular emloyeeid	select employeeid, convert(varchar(10), intime, 112) as thedate, min(intime) as intime, max(outtime) as outtime from yourtable t group by employee, convert(varchar(10), intime, 112) 	0
4153632	26591	mysql - count different fields on different conditions in one joined table	select some_column,        (select count(1)           from table1          where mt.id = joinable_key            and condition1 = 'something'        ) as first_condition,        (select count(1)           from table1          where mt.id = joinable_key            and condition2 = 'something else'        ) as second_condition   from maintable mt 	0
4156766	39346	how to retrieve a comma seperated list for msaccess sql	select id & ",", other & ","  from table 	0.000399228685334461
4164380	24124	tacking number of users logged in over a time period - database design	select year(sample_datetime),        month(sample_datetime),        day(sample_datetime),        hour(sample_datetime),        avg(user_count) from stats group by 1,2,3,4 	0
4182054	29216	select all n between @min and @max	select row_number() over (order by so1.id) from sysobjects so1,sysobjects 	0.000174911631829962
4187026	10906	sql group where clause by employee	select e.name,          coalesce(max(case when e.form = 'abc' then 'yes' end), 'no') as result     from employees e group by e.name 	0.532503077912265
4190617	39452	sql query help!! i'm trying to select the row that doesn't start with a number	select col1   from table1   where substr(col1, 1, 1) not between 0 and 9 	0.0953755250078234
4194986	22497	selecting maximum version number from two columns	select  f.[pkfileid]         ,x.[fkdocumentheaderid]         ,f.[fkdocumentid]         ,x.[version]         ,x.[revision]         ,f.[fileurl]         ,f.[uploadedby]         ,f.[uploadeddate] from    (           select  docs.[fkdocumentheaderid]                   ,max([version] * 100000 + [revision]) as [versionrevision]            from    [clinicalguidancev2].[dbo].[tbl_documentfiles]                   inner join dbo.tbl_documents docs                      on [fkdocumentid] = [pkdocumentid]           group by                   docs.[fkdocumentheaderid]         )as x         inner join dbo.tbl_documentfiles f            on f.[fkdocumentheaderid] = x.[fkdocumentheaderid]               and f.[version] * 100000 + f.[revision] = x.[versionrevision] 	0
4200962	27631	doctrine 2 order by associative tabel	select u from user u join u.attributes a where a.type = 'title' order by a.name asc 	0.442878158232829
4213232	38755	c# (3.5) use tableadapters to read/write null datetime values to a database	select to_char(null_date_field,'dd/mm/yyyy hh24:mi:ss') from * 	0.237188956485799
4223409	11649	how to get data from a table	select playername, (select t2.playername from #temp t2 where t2.playerid = t.captainid  ) from #temp t select t1.playername , t2.playername captain from #temp t1 left join #temp t2 on t1.captainid = t2.playerid 	0.000209108674993545
4228744	37514	mysql data formatting with c# (date) and datetimepicker	selecteddate 	0.36953302340454
4229041	8529	sql server 2008: how to determine permission to create new database?	select * from sys.fn_my_permissions('','') 	0.106963398587892
4252259	3336	select records beginning with defined symbol from database	select * from manufacturer m left join manufacturer_to_store m2s on m.manufacturer_id = m2s.manufacturer_id  where m2s.store_id = <some store id here>     and (m.name like 'b%' or m.name like '9%') 	0.000876082574145142
4270801	38801	dropdownlist values and text need trimmed	select rtrim(cast(dept_name as varchar(50))) as dept_name from depts select rtrim(cast(dept_name as varchar(50))) dept_name from depts select dept_name = rtrim(cast(dept_name as varchar(50))) from depts 	0.408981471030141
4273484	1817	consolidate 2 tables via a mapping table - full joins?	select a.id as a_id, a.desc as a_desc, b.id as b_id, b.desc as b_desc from table_a as a left outer join mapping_table as m on a.id = m.a_id full outer join table_b as b on m.b_id = b.id 	0.0931375706206231
4290394	31211	return multiple fields as a single field value in sql server	select a as c union all select b as c 	0.000345933916663812
4309515	22097	mysql query - accessing field without affecting output	select tableb.name        from tablea  inner join tableb on tablea.ida=tableb.idb       where ida in (1, 2, 3, 4); 	0.177360231329225
4317997	30145	query showing records that do not match in between tables	select q.installationdate, q.quarterlyreporttype, reports.reporttype       from #quarterlyreportsdue q         left outer join reports r             on q.assessmentid = r.assessmentid                 and q.quarterlyreporttype = r.reporttype                   and r.reporttype in ('1st quarterly', '2nd quarterly', '3rd quarterly', '4th quarterly')       where r.assessmentid is null     order by #quarterlyreportsdue.assessmentid 	0.0023982549843124
4322290	14456	mysql query for top 10 users per location	select * from user where user.id = cost_center.id order by total_prints desc limit 10; 	7.07866621634856e-05
4365164	38401	sql selecting distinct count of items where 2 conditions are met	select  product_brandname         , product_classname         , count(*) from    products         join product_brand on products.product_brandid = product_brand.product_brandid         join product_class on products.product_classid = product_class.product_classid               group by          product_brandname         , product_classname 	0
4369126	9319	mysql: return single record with 50 ids, instead of a 50 records with a single id	select group_concat(bookid separator ' ') from tblbook where authorid=9 group by bookid 	0
4373997	324	how to obtain the result by using only 1 query?	select      (bcounts.broswer_counts * 100 / total.total) percentage,     bcounts.broswer from (      select            count(timestamp) broswer_counts,            browser      from            table      where            timestamp > '12/1/2010'      group by            browser) bcounts,  (select count(timestamp) total from table where timestamp > '12/1/2010') total 	0.00297072946846833
4376273	19075	building a basic sql join but need to also include a count	select content.content_id, count(distinct(statistics.user_ip)) as hits from content join statistics on content.content_id = statistics.content_id where statistics.content_id = '37' and statistics.timestamp between '2010-01-01 00:00:00' and '2010-12-31 00:00:00' group by content.content_id 	0.716613466979233
4385346	20689	using sql query to determine if a table exists	select count(*) from all_objects where object_type in ('table','view') and object_name = 'your_table_name'; 	0.118117365629019
4391618	24283	tsql: need help with returning latest record from a table	select   custid, custdate, custcode from   mytable where   not exists   (     select * from mytable as a_mytable     where a_mytable.custid = mytable.custid       and a_mytable.custdate > mytable.custdate   ) 	0.00656772154111004
4401326	7608	sql return only duplicate rows	select     t2.* from     (     select         stateid, orderid, ordertime, permitid     from        mytable     group by        stateid, orderid, ordertime, permitid     having        count(*) >= 2     ) t1     join     mytable t2 on t1.stateid = t2.stateid and t1.orderid = t2.orderid and                    t1.ordertime = t2.ordertime and t1.permitid = t2.permitid 	0.000369422793655263
4402286	15101	how to check if user has system admin privileges in sql server 2008 r2	select is_srvrolemember('sysadmin', 'yourlogin') 	0.433795668319324
4402869	28758	mysql extract results by delimeter	select substring_index(     substring_index(        old_text        ,'info3=',-1),'|',1) from mw_text; 	0.0615426835084062
4426130	37230	mysql query to sum a column from a table where another two columns are unique when combined together	select ofs.folder_group_id, ofs.folder_id, sum( files.number_of_line_of_text)  from ordered_file_stats ofs join files on files.id = ofs.file_id group by folder_group_id, folder_id 	0
4428645	38624	postgres regexp_replace want to allow only a-z and a-z	select regexp_replace('abc$wanto&toremove#special~chars', '[^a-za-z]', '', 'g') 	0.244604067447838
4437650	32214	mysql: select comments and the number of replies they have	select c.id, c.text, count(reply.id) as total_replies from comments c  left join comments reply on c.id = reply.parent_id where c.parent_id is null group by c.id 	0
4441590	24031	how do i combine multiple sql queries?	select worked/available as percentagecapacity from ( select worked from a ),       ( select available from b ) 	0.113532553161599
4446875	39989	mysql sum showing wrong answer for decimal type	select count(*) from  `sales_details`  where  `sales_id` =12 	0.561845696150896
4452260	34732	join tables based on if the id = 2	select columns from sp_comments c inner join sp_transactions t on t.sp_transactions_comment_id=c.sp_comments_id where t.sp_transactions_step_id=2 	4.78384094889276e-05
4471494	16677	how to get list of all stored procs/functions/view which refer a table?	select object_name(object_id) from sys.sql_modules where definition like '%table1%' 	0
4473538	21724	how do i compare a datetime field to a time expressed in minutes using mysql	select data from datatable              where data.createdat > date_sub(now(), interval 5 minute) 	0.000158037078014091
4487036	34882	postgres problem	select t.tran_date,        t.withdraw,        t.deposit,        (select sum(y.deposit) - sum(y.withdrawl)           from your_table y          where y.tran_date <= t.tran_date) as balance,        t.tran_date - coalesce(lag(t.tran_date) over(order by t.tran_date),                                t.tran_date) as days_since_last   from your_table t 	0.77506727731148
4510261	7527	combine these mysql queries	select t1.month, t1.new, t2.returning from (query 1) as t1, (query 2) as t2 where t1.month = t2.month; 	0.212933871094561
4513994	19488	reference a named calculation from another named calculation	select a.type  from account a  join sysdba.contact c on a.accountid = c.accountid where c.cid ={current-table}.cid 	0.0040613240635576
4518754	13812	sql insert multilingual characters	select * from table where column = n'abc' 	0.343551811803729
4519549	14084	how to join 3 relational tables	select  t2.rating from    t1 join    t3 t31 on      t31.id = t1.id join    t3 t32 on      t32.source_id = t31.source_id join    t2 on      t2.id = t32.id where   t1.id = 42 	0.134629495166822
4521300	30710	convert sql to linq to sql	select new {app = gapp.key.appid, model = gapp.key.model, date = gapp.key.date, count = gapp.count() } 	0.628498984954775
4523100	40098	getting the last 30 rows	select * from table order by id desc limit 30 	0
4545314	32386	issue regrading displaying top 10 salaries using row_number()	select salary from (select salary     ,rank() over      (order by salary desc) as 'rank' from user2) salaries where  salaries.rank <= 15 	0.377446109368865
4558107	11587	i have a table which contains data with a date column. mysql query help needed!	select * from `table` where `date` between date_sub(now(), interval 1 day) and now() 	0.0410987156709169
4570679	797	sql to combine data for single row per object	select   coloredobjectid                                         ,          max(colorother) as colorother                           ,          max(case when colorcode = 1 then 1 else 0 end) as yellow,          max(case when colorcode = 2 then 1 else 0 end) as red   ,          max(case when colorcode = 3 then 1 else 0 end) as blue  ,          max(case when colorcode = 4 then 1 else 0 end) as other from     colors group by coloredobjectid 	7.2826430594229e-05
4580458	29167	query results with no reverse	select mt1.usera, mt1.userb, mt1.numberofconnections from mytable mt1 left outer join mytable mt2 on mt1.usera = mt2.userb         and mt1.userb = mt2.usera where mt2.usera is null     or mt1.usera < mt2.usera 	0.414289998821103
4588935	6690	group by - do not group null	select `table1`.*,      ifnull(ancestor,uuid()) as unq_ancestor     group_concat(id separator ',') as `children_ids` from `table1`  where (enabled = 1)  group by unq_ancestor 	0.656078051607913
4611472	23148	mysql with 3 group by and sum	select currency_id,        sum(case              when type = 'cash_in' then amount            end) as cash_in,        sum(case              when type = 'cash_out' then amount            end) as cash_out,        sum(case              when type = 'cash_in' then amount              else -amount            end) as balance from   tb_cash_transaction where type in ('cash_in', 'cash_out') group  by currency_id 	0.161733705005553
4613054	31607	count items in each category	select item_id, category_id from table group by item_id, category_id having count(*) > 1 	0
4617691	31356	sql: how to find duplicate values in a large table	select sku from table group by sku having count(sku) > 1 	0.000286871682365657
4621362	28245	calculate difference between two time()	select `id`   from `table`  where date_sub(now(), interval 1 day) > from_unixtime(`date`) 	0.000189662865325792
4636880	30696	t-sql query, combine columns from multiple rows into single column	select  'r-' + cast(r.number as varchar(32)) as requisitionnumber ,       (         select  'po' + cast(ip.number as varchar(32)) + ';'         from    issuedpo ip         join    requisitionitems ri         on      ip.id = ri.issuedpoid         where   ri.requisitionid = r.id         for xml path('')         ) as polist ,       (         select  'j-' + cast(j.number as varchar(32)) + ';'         from    job j         join    job_activity ja         on      j.id = ja.jobid         join    requisitionitems ri         on      ri.job_activityid = ja.id         where   ri.requisitionid = r.id         for xml path('')         ) as joblist from    requisition r 	0
4639052	12775	user's possibilities on site	select action, if(sum(count) < min(limits), 1, 0) as can_do_action from log left join rules on rules.action = log.action where userid = xxx and rating_min <= rating and rating_max >= rating and ignore = 0 and datediff(date, now()) <= days 	0.141760710575445
4645600	10899	select query giving different results	select  count(*) count  from    conflux.dbo.sabr_master m  where   m.email in (select  top 26                              l.email                      from conflux.dbo.sabr_master l                      where (l.titleid in (   select  titleid                                              from    sabr_titlemasters                                              where   isdisplay=1 and                                                       (title like '%account executive%' or                                                      title like '%account manager%' or                                                      title like '%accounts manager%' or                                                      title like '%admin%')))                     order by l.email) and          m.email not in (select  email                          from [sample client].dbo.comm_companydata) 	0.272794486708436
4660383	18440	how do i cast a type to a bigint in mysql?	select cast(conv('55244a5562c5566354',16,10) as unsigned integer); 	0.409151343038559
4668747	1900	mysql merging two fields from two tables into one field in result set	select  * from    (         select  itemid, key, iv.value, s.value as svalue         from    integervalues iv         join    strings s         on      s.id = iv.value         where   iv.itemid = 1         union all         select  itemid, key, null, value         from    stringvalues sv         where   sv.itemid = 1         ) vals join    items i on      i.id = vals.itemid 	0
4669779	14072	fine alphabet in number in sql	select * from mytable where number like '%[^0-9]%' 	0.530585096520372
4672523	13220	sql server 2000 - how do i rotate the results of a join in the final results of a query?	select a.id,        a.name,        stuff(min(str(b.id, 10) + b.information), 1, 10, '') as informationa,        case          when count(b.id) = 2 then stuff(max(str(b.id, 10) +                                    b.information), 1, 10, '')        end                                                  as informationb from   tablea a        left join tableb b          on a.id = b.nameid group  by a.id,           a.name 	0.0471365407005438
4672644	20408	mysql query where column like column	select *    from group g    join contacts c on find_in_set(c.id, g.primary)                   or find_in_set(c.id, g.secondary) 	0.380151895610988
4696845	12640	optimize mysql with order by, group by and one million rows	select testappinstallations.installation_id, testappdata.data_value_num as num1 from testappinstallations left join testappdata on testappinstallations.installation_id = testappdata.installation_id and testappdata.data_id =1 group by testappinstallations.installation_id order by testappdata.data_value_num desc  limit 0 , 20 	0.203911018794802
4697624	26810	querying for things near a geolocation?	select id, hike_title, lat, lng, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122.517349) ) + sin( radians(37.780182) ) * sin( radians( lat ) ) ) ) as distance from my_awesome_table having distance < 10000 order by distance limit 0 , 50 	0.705663461701045
4698580	34793	calculating average speed from columns that have both a distance and a time (null issues)	select sum(distance)/sum(time) as avgspeed from yourtable where distance is not null and time is not null 	0.000281359260312002
4708715	21163	sql query for getting count on same table using left outer join	select m.month, s.success, count(t.month) from (select distinct month from tbl) m cross join (select -1 success union all select 1 union all select 0) s left join tbl t on t.month = m.month and t.success = s.success group by m.month, s.success 	0.56395625410847
4710278	39463	php mysql query array field	select * from pictures where find_in_set(14,tagged); 	0.106673825240478
4711719	2507	change default dateformat stored in a database	select stuff(convert(char(7), getdate(), 120), 5, 0, '-' + convert(char(2), getdate(), 3)) 	0.460350052137041
4713476	40915	how to get csv value for following scenario	select accountnumber,         stuff((select ',' + product                    from yourtable t2                    where t2.accountnumber = t1.accountnumber                    order by product                    for xml path('')),1,1,'') as productstring     from yourtable t1     group by accountnumber 	0.00806411668718103
4715400	31717	how to pull unique results	select ct.*     from childtable ct         inner join (select parent_id, max(order) as maxorder                         from childtable                         group by parent_id) q             on ct.parent_id = q.parent_id                 and ct.order= q.maxorder 	0.00392055384869755
4716438	41034	oracle subquery top 1 result	select * from (     select *, row_number() over (partition by b order by c) as rn     from mytable ) as t1 where rn = 1 	0.207357274165584
4740583	20565	mysql: specifying the order i'd like rows returned in	select *      from `table`     where some_column in(1,58,22,9) order by find_in_set(some_column, '1,58,22,9') 	0.00738385297736235
4744269	13332	oracle: list of schedules	select *   from user_scheduler_schedules 	0.044616000077784
4746302	30745	mysql query - searching in a joined table without filtering records	select     user.*,     group_concat(user_tags_to_return.tag separator ", ") as `tags` from     user left join     user_tag user_tags_to_filter on     user_tags_to_filter.user_id = user.id left join     tag tags_to_filter on     tags_to_filter.id = user_tags_to_filter.tag_id where     tags_to_filter.tag like "%engineer%" or     tags_to_filter.tag like "%programmer%" left join user_tag user_tags_to_return on user_tags_to_return.user_id = user.id left join tag tags_to_return on tags_to_return.id = user_tags_to_return.tag_id group by     user.id 	0.00391087363725176
4751760	31225	pull row with lowest number in a column	select post_id, min(topic_id)     from yourtable     group by post_id 	0
4751946	29868	sql server: use left join to select a column from two tables as a single column	select email from tablea union select b.email from tablea a join tableb b on a.id = b.tablea_id 	0.00164651584128851
4752654	32230	select a scalar value from a table	select @configvar = s.examplesetting    from settings s  where s.settingid = 1 	0.00465572286651468
4756352	7814	sqlite date sorting problem	select type, form_date from table1 union select type, form_date from table2 	0.612395822183586
4759248	40874	difference between two dates in mysql	select timediff('2007-12-31 10:02:00','2007-12-30 12:01:01') * 24*60*60; select timestampdiff(second,'2007-12-30 12:01:01','2007-12-31 10:02:00');  	0.000639983501004383
4762529	3211	is there a way to include duplicates from mysql query: select..from..where..id in (list)	select * from table inner join (    select 1 as sort, 2 as value union all    select 2, 4 union all    select 3, 6 union all    select 4, 1 union all    select 5, 1 union all    select 6, 2) x on x.value=table.id order by x.sort 	0.0241635091262785
4768728	32759	sql: show description in text instead of bit value	select case mybit when 1 then 'valid' when 0 then 'invalid' end as mycolumn from [table] 	0.00116095131928484
4788451	30209	mysql select record where primary key = x	select * from bb_bulletin where (officecode, issuerid, bulletindtm) = (20001, 1, '2011-01-07 14:04:40'); 	0.000775953315696797
4792572	10658	it is possible to do a autonumber sequence in a select on oracle?	select    rownum from    dba_objects,    dba_objects where   rownum <= 9000; 	0.688569475224475
4799919	13208	android: knowing when all items in a database have their field set to the same value?	select exists   (select * from t    where val != (select val from t limit 1)) 	0
4812115	15176	mysql query help - count rows	select left(eventname,instr(concat(eventname,':'),':')) as prefix, count(*) from trackingevent group by left(eventname,instr(concat(eventname,':'),':')) 	0.465231889545033
4850478	13386	get data in sql from from date to to date	select ... from ... where somecol >= '2011-01-01' and somecol <= '2011-01-30' 	0
4856568	27002	query to get column value comma separated	select wm_concat(name) from customer; 	0
4857386	23459	how can i speed up this view which sums a load of quote line rows?	select dbo.quoteline.qid, sum((dbo.pricelist.listprice - dbo.quoteline.voff) * dbo.quoteline.quantity) as total from dbo.quoteline  inner join dbo.pricelist on dbo.quoteline.prodcode = dbo.pricelist.prodcode  inner join dbo.quote on dbo.quote.qid = dbo.quoteline.qid  inner join dbo.client on dbo.client.cid = dbo.quote.cid  where     (dbo.client.pricetype = 'v') group by dbo.quoteline.qid 	0.438955665749491
4859473	2803	select todays date to get the record	select * from table1  where date(modify_date) = curdate(); 	0
4864741	919	select id where count(*) > x ? - how to get records from any user that has more than x records in table?	select id   from (         select id, count(*) as cnt         from sowewhere          group by id         having cnt > 1    ) temp_table 	0
4867279	20091	sql get specific time in date	select * from tbl where datecol between dateadd(hour,21,datediff(d,0,getdate()-1))   and getdate() 	0.000922026298274636
4872655	37042	mysql - limiting group bys	select * from products p where p.id in (select p1.id from products p1      where p.category = p1.category order by price limit 0,2) and price = (select min(price) from products p2      where p2.sub_category = p.sub_category) 	0.618638600441361
4883095	10901	how to generate the date	select id, [date], intime, outtime,              case                  when outtime > intime then                      [date]                  when outtime < intime then                      convert(                             nvarchar,                             dateadd(                                     dd,                                     1,                                     convert(                                             datetime,                                             substring([date],1,4)+'-'+substring([date],5,2)+'-'+substring([date],7,2)                                             )                                     ),                             112                             )                  end as newdate 	0.00630528392743391
4893837	5219	sql query dependant column	select k.*   , case       when tkl.id is null       then null       else 'selected'     end as selected from keywords k   left join (       select distinct templateid       from templatekeywordlink     ) as tkl     on k.id = tkl.templateid 	0.242291912784448
4896914	21097	mysql match against multple values	select nid from table where tag_id in (tag1, tag2, tag3, ...) group by nid having count(*) = n; 	0.045413618090603
4897130	29631	sql find same column data	select a.id, a.col1, a.col2, a.col3 from mytable a, mytable b where a.id != b.id and a.col1 = b.col1 and a.col2 = b.col2 and a.col3 = b.col3 	0.000885879603051545
4911582	2148	finding "missing" rows	select u.u_id, q.s_id, count(a.q_id)  from users u cross join questions q left join answers a on q.q_id = a.q_id and u.u_id = a.u_id and q.correct = a.answer group by u.u_id, q.s_id 	0.00790491161056507
4935837	8235	php list while loop	select title,        event_date,        event_time,        location,        group_concat(username separator ', ') as username   from bs_events    left join bs_reservations          on bs_reservations.id_event = bs_events.id     group by bs_reservations.id_event            bs_events.title,           bs_events.event_date,           bs_events.event_time,           bs_events.location  order by bs_events.eventdate asc limit 20 	0.158082454748199
4937122	38152	multiple reference to primary key in a table in mysql	select d1.density, d2.color, s1.length, s2.breadth, o.or_id      from order_de o         inner join density d1             on o.density = d1.de_id         inner join density d2             on o.color= d2.de_id         inner join size s1             on o.length = s1.si_id         inner join size s2             on o.breadth = s2.si_id     order by o.or_id asc 	0.00334780887356622
4942902	21582	mysql join using "contains"?	select id, name, data, nid, description   from orders inner join nodes on data like concat('%;i:', nid, ';%') 	0.444919395375782
4948356	14191	query to show all tables and their collation	select table_catalog, table_schema, table_name, column_name, collation_name     from information_schema.columns 	0.00175456991545604
4950999	31782	mysql: multi-column join on several tables	select a.*, e.citympg, e.hwympg from table1 a   join table2 b on a.makeid=b.makeid   join table3 c on a.modelid=c.modelid   join table4 d on a.catid=d.catid   join table5 e on b.makename = e.make                 and c.modelname = e.model                 and a.caryear = e.year   where a.carid = $carid; 	0.120404290984088
4952037	18801	mysql: multi-column join on several tables part ii	select a.*, e.citympg, e.hwympg from table1 a join table2 b on a.makeid=b.makeid join table3 c on a.modelid=c.modelid join table4 d on a.catid=d.catid left join (select year, make, model,                    avg(citympg) as citympg,                    avg(hwympg) as hwympg                       from table5             group by year, make, model) e on b.makename = e.make                                          and c.modelname = e.model                                          and a.caryear = e.year where a.carid = $carid; 	0.416139378627565
4959456	32189	database object related to the view - sql server 2005	select object_name(object_id) from sys.sql_modules where definition like '%mytable%' 	0.126051434757622
4970477	31806	oracle/sql: wm_concat & order by	select task_card, wm_concat(code) as zones from (select task_card, code, control_category from odb.task_card_control        where odb.task_card_control.control_category = 'zone'       order by code) group by task_card 	0.504739066920875
4980368	6466	how to check data is inserted or not in stored procedure	select @@rowcount 	0.291740337079248
4988030	14801	how can i count unique records from a column in my mysql database?	select referrer, count(*) as numberofhits from yourtable group by referrer 	0.000158143495332381
4989129	4307	combine multiple count statements into single select statement	select count(*) as total_attempts,   count(case when correct = true then 1 else null end) as score from assessment where student_id = 1 group by lesson_id 	0.00986833538545579
4998047	9238	sql handling nullible foreign keys in where clause	select min(table_pk) from my_table  where      ((x_fk = (select x_pk from x where x_name = ?)) or (? is null and x_fk is null)) and      ((y_fk = (select y_pk from y where y_name = ?)) or (? is null and y_fk is null))  and      ((z_fk = (select z_pk from z where z_name = ?)) or (? is null and z_fk is null)) 	0.680966843322721
5007122	14542	how to select two additional columns from another table based on values in the main table?	select m.*, u1.name, u2.name from maintable m  inner join users u1 on (m.userid1 = u1.userid) inner join users u2 on (m.userid2 = u2.userid) 	0
5017680	3158	mysql select join where and where	select products.*  from products join producttags on products.id = producttags.product_id where producttags.tag_id in (1,2,3) group by products.id having count(distinct producttags.tag_id) = 3 	0.701935468331616
5019485	3801	simpler way to get a diff of 2 mysql tables?	select distinct a, b, c from first  where (a, b, c) not in (select a, b, c from second) 	0.00284491142387826
5021027	31195	how do i exclude auto generated columns from sql server generate script data only?	select col1, col3, col6 from mytable 	0
5025757	11106	mysql subquery reuse	select     username,     distance from ( select     username,     @d:=distance as distance,     @c   := if(fp = 0                and dp is null                and @d>=@max, @c+1, @c),     @max := if(fp = 0                and dp is null                and @d>=@max                and @c <= 5, @d, @max) maxof5dist from (select @max:=-1000, @d:=null, @c:=0) m inner join ( select     username, # others taken out for brevity     users.fp, deflects.dp,     glength(linestringfromwkb(linestring(asbinary(             pointfromtext('point({$geolat} {$geolong})')), asbinary(location))))             as distance from users cross join venues on users.vid = venues.vid left join deflects on users.username = deflects.defender where username not like '{$mysql['username']}'   and username not like '{$users['king']['username']}'   and venues.location is not null order by distance ) x ) y where vid = '{$vid}' or distance <= maxof5dist order by distance 	0.504640242191327
5030201	30467	building sql query for a table structure	select     seatpref,     count(seatpref) as prefcount from     bookings b group by     seatpref order by     count(seatpref) desc 	0.572260324271428
5043159	34209	find duplicates for several columns exclusive id-column	select * from @t as t1 where exists (select *               from @t as t2               where                 t1.id <> t2.id and                 t1.c1 = t2.c1 and                 t1.c2 = t2.c2 and                 t1.c3 = t2.c3) 	0.00149231349285383
5045359	33792	mysql group_concat(query)	select   group_concat(brands.brand_name)  from                                                                  vehicles  inner join brands on vehicles.id=brands.id   inner join cars on cars.id=vehicles.id                        where                                                                 cars.id = vehicles.id 	0.327086913543303
5050745	33682	select * from help	select dataa from stats where id=1; 	0.376546191118779
5060782	13108	mysql query with 2 columns in table a related to 1 column in table b	select u1.name as send, u2.name as receive from mail m inner join user u1 on m.sender = u1.guid inner join user u2 on m.receiver = u2.guid 	0
5063989	34298	limit results in mysql query	select max(i.uploaddate) group by (u.id) 	0.483383888347656
5071011	15197	mysql cross check tag query	select * from items i inner join tags t on i.id = t.id where t.tag = "foo" and not exists (     select *     from items ii     inner join tags tt     on ii.id = tt.id      where tt.tag = "bar" and tt.id = t.id) 	0.477016970093742
5074114	33554	different count from 2 tables	select a.productid,         a.catid,         a.totalsales,         b.totalpromotion  from   (select p.productid,                 p.catid,                 count(s.productid) as totalsales          from   products p                 left join sales s                   on p.productid = s.productid          group  by p.productid,                    p.catid) a         inner join (select p.productid,                            p.catid,                            count(s.productid) as totalpromotion                     from   products p                            left join promotion s                              on p.productid = s.productid                     group  by p.productid,                               p.catid) b           on a.productid = b.productid 	0.000311797350448699
5088577	20833	return a boolean value from a select query	select field1, field2, cast(1 as bit) as is_field from table 	0.00317567274951224
5102134	34011	how to group text columns into one column	select dt,'c1' as col,c1 from table1 where c1 is not null union all select dt,'c2' as col,c2 from table1 where c2 is not null union all select dt,'c3' as col,c3 from table1 where c3 is not null union all select dt,'c4' as col,c4 from table1 where c4 is not null 	0.000193218724743777
5103307	1509	how to get top 25 records order by createdon using sql query?	select  top 25          ut.*         ,u.username         ,u.password from    [updatetext] ut join    users u on  ut.userid = u.userid join    (   select  max(ut2.createdon) as maxcreatedon                     ,ut2.userid             from    [updatetext] ut2             group by ut2.userid         ) x on x.maxcreatedon = ut.createdon             and x.userid = ut.userid order by ut.createdon desc 	0.00279938629254816
5113190	9957	mysql join to same table	select e1.bundle_id as b_id, e1.product as prod, e1.id as id,  e2.bundle_id as b2_id, e2.product as prod2, e2.id as id2, e3.bundle_id as b3_id, e3.product as prod3, e3.id as id3, e4.bundle_id as b4_id, e4.product as prod4, e4.id as id4,     from `staging` as e1 inner join `staging` as e2 on (e1.bundle_id = e2.bundle_id and e1.id != e2.id) left join `staging` as e3 on (e1.bundle_id = e3.bundle_id and e2.id != e3.id and e3.id != e1.id and e3.product != 'h') left join `staging` as e4 on (e1.bundle_id = e4.bundle_id and e3.id != e4.id and e4.id != e2.id and e4.id != e1.id and e4.product != 'h') where e1.bundle_code = '10' and e2.bundle_code = '20' and e2.product = 'h'; 	0.0244799764523728
5116979	2608	ado.net getting fields from a datareader by field and table name	select         oa.id as ordine_articolo_id,          ... 	0.00233543673026302
5117663	26756	how to find names with special characters like 'josé' on ms sql-server	select *  from venue  where name collate sql_latin1_general_cp1_ci_ai like '%cafe%' 	0.0526237637819095
5128784	2544	mysql - select concatenate 2 values with 1 id	select id,group_concat(distinct place order by place asc separator ',')  from map group by id 	6.77164226408337e-05
5159593	8353	how do i order a list in mysql so that a specific id always shows up first?	select * from table  order by case when id = 2 then 0 else id end 	0.00011775197909374
5159784	30572	tsql union of sub queries that each require an order by clause	select *    from (select top 5 *            from [geo].[areas]           where countryid = @countryid             and (typeid = 'city')       order by [shapearea] desc) as biggestcities union all select *    from (select top 5 *            from [geo].[areas]           where countryid =  @countryid             and (typeid = 'national park')       order by [shapearea] desc) as biggestparks 	0.170142804080587
5159869	12741	how to use case to get 3 columns from a single column?	select     case linenumber when 19 then dollaramt end as aamt,     case linenumber when 20 then dollaramt end as pamt,     case when linenumber <> 19 and linenumber <> 20         then damt     end as damt from datadollar 	0.000131213690902837
5166344	11130	mysql count totals by year and month	select date_format(created, '%y') as 'year', date_format(created, '%m') as 'month', count(id) as 'total' from table_name group by date_format(created, '%y%m') 	0.000289481577854323
5166753	2302	how do i extract unique values from sql?	select user_id from table group by(user_id) having count(user_id) = 1 	0.000286929813186036
5169884	4102	oracle/sql - finding records with one value excluding by similar record	select person from table group by person having min(type) = 's' and max(type) = 's' 	0
5182990	25236	boolean expression as column value in transact sql	select (5 - 3) 	0.637410963425513
5183893	23327	database normalization precautions	select distinct clothingtype from bigtable into clothingtypes; 	0.587630708099375
5212313	4440	how do a populate a drop down menu from a database without repeating the data?	select id, name from $tbl_name group by id, name 	0.000629680782768357
5223980	4990	what is the sql query in sqlite, to retrieve the records from the database table for the last week, for the last month, and for the last year	select * from database_table     where strftime('%y-%m-%d',date) >= date('now','-6 days') and      strftime('%y-%m-%d',date)<=date('now') order by date 	0
5234529	26105	php/mysql select order by given id	select ... order by id = 12 desc, id 	0.0020722305500599
5234981	2307	sql union all with a inner join	select     coalesce(table1.dwg,table2.dwg),     table1.part,     table1.qty,     table2.order,     table2.part,     table2.qty, from table1 full outer join table2 on      table1.dwg = table2.dwg and     table1.part = table2.part 	0.586728663711533
5257704	21683	how to create a mysql join query with hierarchical data	select *  from fields as f inner join groups as g  on g.group_id = f.parent_group  order by group_order, field_order 	0.527391182922141
5275623	21448	finding common value in two columns	select column2     from yourtable     group by column2     having count(*) = (select count(distinct column1) from yourtable) 	0
5277097	40518	select all table with join by where	select table1.id, table1.name, table2.param from table1  left join table2 on table1.id = table2.id and table2.param='x' 	0.0447969285518884
5283849	31262	mysql join with time matching	select j.id, j.starttime, j.endtime, j.jobname, c.cpuusage from (     select j.id, j.starttime, j.endtime, j.jobname, max(c.usagetime) as usagetime     from jobinfo as j     left join cpuinfo as c     on c.usagetime <= j.starttime     group by j.id ) as j join cpuinfo as c on j.usagetime = c.usagetime 	0.0991730145060737
5287246	29607	mysql join and exclude?	select * from `b` where `id` not in (select `id` from `a`) 	0.161829353314917
5297047	12692	find duplicates in mysql	select yearmonth, count(user) from (   select     user   , date_format(loggedintime, '%y-%m') as yearmonth   from user_logins   group by user, yearmonth   having count(*) > 5 )group by yearmonth 	0.0385541794686886
5297602	20865	check mysql db size through rails	select table_schema 'database', concat( round( sum( data_length + index_length ) / ( 1024 *1024 ) , 2 ) , 'm' ) size from information_schema.tables where engine=('myisam' || 'innodb' ) group by table_schema; 	0.29631807914503
5311420	21376	mysql query that returns only the "common" columns for a group of rows (and php if needed)	select codpais, codauto, codprov, group_concat(distinct codpobl) as pobl  from projects  where area=1 group by codpais, codauto, codprov 	0
5312198	11519	simple sql query problem: how to only "select" items from table_a which are also in table_b	select a.wbcode from countrieslist_a a inner join countrieslist_b b on a.wbcode = b.wbcode 	0.00479840572003355
5323511	7727	sql query to obtain pair links	select c.project_name, d.project_name from projpart a inner join projpart b   on a.memberid = b.memberid      and a.projectid < b.projectid inner join project c on c.projectid = a.projectid inner join project d on d.projectid = b.projectid 	0.0272155133960522
5327799	21830	number of records in a table in sql	select info.isd, data.ispnname, data.diskname, count(*)  from data, info where data.reconciled = 0 and     data.filled = 1 and     data.sub_needed = 1 and     data.deleted = 0 and     data.contract_date >= 'start date' and     data.contract_date <= 'end date' group by data.diskname 	0.000216023219514346
5338605	26405	select the result of a comparison in sql statement	select (case when (1 < 2) then 'true' else 'false' end) as one,        (case when (1 > 2) then 'true' else 'false' end) as two from table 	0.152432116829559
5340883	7685	mysql avg to ignore zero	select avg(nullif(field ,0))  from table 	0.240377065151518
5340975	27545	sql server : get at the name of the app causing an update in a trigger	select app_name() 	0.0210082614846341
5360488	3264	sort my database data	select  * from    (     select * from table order by score desc, income asc limit 0,5      ) t order by income 	0.140112667173863
5376465	12373	sql server 2 views in one	select   count(*) as grandtotal,   count(case when [bla bla] then 1 end) as total   (select top 1 a from y) as a from x where id = 1 	0.0272590977183453
5381201	23296	how do i write a query that returns the number of records in a particular status out of the last twenty (but only if those twenty happened today?)l	select test_id       ,count(*)               as num_runs       ,sum(status)            as passed       ,count(*) - sum(status) as failed   from test_results  where date_ran = current_date  group      by test_id  having count(*) >= 20    and count(*) - sum(status) >= 10; 	0
5386188	10626	how to output to csv file using mysql?	select user_id, user_phone into outfile '/your/filepath'   fields terminated by ',' optionally enclosed by '"'   lines terminated by '\n'   from user_details; 	0.117898344966225
5388715	13257	sql: how to find unused primary key	select * from table_a a  where not exists (select * from table_b where fk_id = a.id)    and not exists (select * from table_c where fk_id = a.id)    and not exists (select * from table_d where fk_id = a.id)    ... 	0.0034513314563072
5389751	32812	check for time overlap (ruby/mysql)	select count(*) from tab as t where    :param_start between t.start_time and t.end_time or    :param_end   between t.start_time and t.end_time or    (:param_start <= t.start_time and     :param_end >= t.end_time    ) 	0.0282491773869835
5392795	15055	convert to % for a count sql	select   del_cd, count(del_cd) * 100.0 / sum(count(del_cd)) over () from     datastore group by          del_cd 	0.113178472619158
5399915	25024	how can i conditionally join two mysql tables on multiple fields?	select  a.* from    pos_tables a left join         pos_user_login b1 on a.staff1=b1.staff_id left join         pos_user_login b2 on a.staff2=b2.staff_id left join         pos_user_login b3 on a.staff3=b3.staff_id left join         pos_user_login b4 on a.staff4=b4.staff_id where  (b1.staff_id is not null or          b2.staff_id is not null or         b3.staff_id is not null or         b4.staff_id is not null) 	0.00455620563938499
5400810	38652	sql for displaying and sorting messages and their replies in one table	select main.*, count(reply.id) as cnt_replies, max(reply.datetime) as max_datetime from posts as main left join posts as reply     on main.id = reply.reply_id group by main.id having main.reply_id is null order by max_datetime desc 	0.000269020440240921
5406170	19019	sql grouping by month and year	select cast(month(date) as varchar(2)) + '-' + cast(year(date) as varchar(4)) as mjesec, sum(marketingexpense) as sumamarketing, sum(revenue) as sumazarada  from [order] where (idcustomer = 1) and (date between '2001-11-3' and '2011-11-3') group by cast(month(date) as varchar(2)) + '-' + cast(year(date) as varchar(4)) 	0.00103438250483861
5428129	32171	trouble writing mysql query involving ordered data from three tables	select tags.tagname from (select tagid, count(*) from  coupon_tags   join coupons on coupons.couponid = coupon_tags.couponid and zone = 'los angeles'   group by tagid order by count(*) desc limit 10) as most_used join tags on most_used.tagid = tags.tagid 	0.142199020414934
5435376	39349	compute average for three periods of times	select       avg(price) as aggregatedprice     , count(*) as pcount     , avg(case when datediff(day, updateddatetime, getdate()) < 7 then price else null end) as aggregatedprice7days     , sum(case when datediff(day, updateddatetime, getdate()) < 7 then 1 else 0 end) as aggregatedprice7days     , avg(case when datediff(day, updateddatetime, getdate()) < 30 then price else null end) as aggregatedprice30days     , sum(case when datediff(day, updateddatetime, getdate()) < 30 then 1 else 0 end) as aggregatedprice30days from     dbo.products where     id = @id 	0.000140953765287532
5451077	39971	query to find the ssis package run schedule	select * from   msdb.dbo.sysmaintplan_plans p        inner join msdb.dbo.sysmaintplan_subplans sp          on p.id = sp.plan_id        left outer join msdb.dbo.sysjobschedules j          on j.schedule_id = sp.schedule_id 	0.334305687623913
5456471	38137	finding multi column duplicates mysql	select t.id, t.a_id, t.b_id from (   select a_id, b_id   from tbl   group by a_id, b_id   having count(*) > 1) x, tbl t where x.a_id = t.a_id and x.b_id = t.b_id order by t.a_id, t.b_id 	0.0173463362319962
5458176	28840	mysql select: returning multiple columns based on a column value in the same table	select * from file where (acl = 0) or (acl = 1 and ? = 'true') or (acl = 2 and ? = fileownerid) 	0
5470880	30701	how do i select the min from a function in sql?	select min (datediff(day, date_col, getdate())) from tb1 	0.0409965067467983
5472790	36433	mysql how to include in where two clause?	select    cms_module_ladu_batch.id as batch_id,           cms_module_ladu_batch.date_changed as date_ch,           kogused.kogus as kogus,           sum(kogused.kogus) as total  from      cms_module_ladu_batch  left join kogused on cms_module_ladu_batch.id = kogused.bid  where     t2 != 'sildid'  group by  batch_id having    (        (           cms_module_ladu_batch.date_changed < date_sub(now(), interval 1 month)           and sum(kogused.kogus) > 0        )     or            cms_module_ladu_batch.date_changed > date_sub(now(), interval 1 month)            ); 	0.242418206181596
5480178	23671	using like tsql with a list of values	select s.* from students s (nolock) join @tmparticles a   on s.articles like '%' + a.article '%' 	0.050185229354754
5488968	16730	combine two sql statements, set a status	select name, id, case       when date1 < sysdate then 1       when date2 < sysdate then 2 end as status from mytable where date1 < sysdate or date2 < sysdate 	0.00662957684171354
5493389	26521	mysql select counter, group by	select @rn := if(@g = tbl_albums.id, @rn+1, 1) rownumber,        tbl_tracks.title, tbl_albums.title,   @g := tbl_albums.id from (select @g:=null, @rn:=0) initvars cross join tbl_tracks inner join tbl_albums on tbl_tracks.album_id = tbl_albums.id order by tbl_albums.id, tbl_tracks.title; 	0.312706238920682
5494338	8887	how to find person who has posted maximum number of events	select    users.id,      count(events.id) as events_count   from users inner join events on users.id = events.user_id   group by       users.id   order by      count(events.id) desc limit 1 	0
5509376	23799	error adding a foreign key constraint	select * from route where rid not in (select rid from reservation) 	0.0283944945152081
5511357	4840	query from two tables with one statement?	select ip, userid, group from logs inner join user on logs.userid = user.userid where ip = '1.2.3.4' 	0.00509228435059574
5518673	35649	how to automatically convert a mysql column to lowercase	select id, lower(my_column) as my_column_lowercase from my_table; 	0.0250636952760008
5525407	1716	how to count 2 different data in one query	select     sum(case when persons.name = 'john' then 1 else 0 end) as johncount,     sum(case when persons.name = 'john' and persons.age > 30 then 1 else 0 end) as oldjohnscount,     count(*) as allpersonscount from persons 	0.000312017053499127
5526002	15417	sql select field dependent of another field in row	select title       ,entry_date       ,case when channel_id = 1 then field_id_4             when channel_id = 2 then field_id_10         end as initial_cost   from exp_channel_data; 	6.593460481915e-05
5550487	6501	mysql combine rows?	select itemid, count(*)/2*100 as percent from     ( select itemid from extra_field_values where fieldid = 201 and value = 6     union all     select itemid from extra_field_values where fieldid = 193 and value = 1 ) as t group by itemid; 	0.0132779394525697
5552797	37908	sorting before grouping, and vice-versa : which is faster?	select a, sum(b) from (     select a, b     from c     order by a      ) d group by a 	0.533101192168427
5580903	13357	mysql - merge first query results into a column of the second query	select name,        select group_concat(name order by id separator '\')          from foldertable          where id between (select max(id)                             from foldertable                            where id < imagetable.folder_id                              and path is null)                       and imagetable.folder_id  from imagetable where id = 2 	0
5582296	595	is there any system defined function to check if user has alter permission?	select * from fn_my_permissions(null, 'database') 	0.288275976050337
5587346	2663	retrieve a user whose one column field is blank	select * from student where course = '' or course is null 	0
5589867	38349	mysql:how to show data from 1 column which separated by comma?	select group_concat(serial_number ) from data; 	0
5595973	215	data validation optimisation	select student_id from student where student_id in (student, ids, from, your, batch, file) 	0.720888902976577
5611377	7412	pl/sql how do i select into table type local variable	select distinct case1.customer_id bulk collect into l_customers from case case1   where case1.case_id in (select column_value from table(a_case_id_list)) and     not exists (select 0 from case case2 where case2.customer_id = case1.customer_id and       case2.lifecycle_code not in (code_id('lifecycle','a'), code_id('lifecycle','d'))); 	0.0582129382167209
5616865	26931	how to apply the minus efficiently on mysql query for tables with large data	select           nm.*, nmgx.*     from nl_members nm    inner join nl_member_group_xref nmgx       on nm.member_id = nmgx.member_id     left join (select                        nmgx2.member_id                  from nl_member_group_xref nmgx2                 where nmgx2.group_id <> 1) nmgx22       on nmgx22.member_id = nm.member_id    where nmgx22.member_id is null    group by nm.member_id; 	0.16326931643418
5624592	33368	sql same unit between two tables needs order numbers in 1 cell	select      unitid,      stuff((select ', ' + convert(varchar, workordernumber)             from tblworkorders t2 where t1.unitid = t2.unitid             for xml path('')),           1,2,'') workordernumbers from tblworkorders t1 group by unitid 	6.03747917796594e-05
5629576	28289	mysql query between multiple dates in another table	select users.name, users.signin, users.signout, sum(case when complete.start between users.signin and users.signout then 1 else 0) as available, sum(case when complete.start between users.signin and users.signout and users.user_id = complete.user_id then 1 else 0) as worked from users inner join logins on users.user_id = logins.user_id, complete group by users.name, users.signin, users.signout 	0.000623571762780989
5634393	7375	getting monthandyear name in sql?	select datename(month, getdate()), datename(year, getdate()); 	0.0933807379554816
5634501	37407	how to write a column name with dot (".") in the select clause?	select max(value) as [prmtable.value] from temptable 	0.0761445959273156
5647857	14719	mysql optimize query: trying to get average of subquery	select   avg(time) from  (   select     unix_timestamp(max(datelast)) - unix_timestamp(min(datestart)) as time   from     table   where     product_id = 12394 and datelast > '2011-04-13 00:26:59'   group by     id ) 	0.0697866264077013
5651526	38187	select multiple columns into one field breaks if one or more columns are empty	select coalesce (somecolumn, 'default-if-column-blank') 	0
5654894	29562	sql: find based on previous id	select t1.person, min(t1.id) as successid     from tries t1     where t1.succeeded = 1         and t1.person in (select t2.person                               from tries t2                               where t2.succeeded = 0                                   and t2.id < t1.id)     group by t1.person 	0
5684279	13006	mysql statement to get a column's value from all rows where another column's value = a specified value	select student from table_name where teacher = 'charles' 	0
5690660	2752	how do i display content from a mysql db in php	select url,fn from $dbtable where url like '%link-one' order by order asc 	0.000613792496741024
5693259	16569	how can a query multiply 2 cell for each row mysql?	select      pieces, price,      pieces * price as 'total'  from mytable 	0
5698087	2541	how to compare two rows or get the fields which value is not match with the rows that compared?	select   orderid,   case min(field1) when max(field1) then 0 else 1 end as field1,   case min(field2) when max(field2) then 0 else 1 end as field2,   ... from atable group by   orderid 	0
5711790	37547	is there any difference in performance of resultset and scrollable resultset?	select *,(select count(*) from table) as counting from table; 	0.536288927703458
5714661	35231	problem querying mysql db	select code, codeid, status from authcodes where 'dsfffmubbdg345qwewqe' like concat('%', code, '%') 	0.747544953541145
5721472	34228	transform sql query to oracle	select case (select timeatt from reader where panelid = devid and readerid =         machine)           when '1' then 'p10'           else 'p20'         end         || '0001'         || to_char(event_time_utc, 'rrrrmmddhh24miss')         || to_char(event_time_utc, 'rrrrmmddhh24miss')         || lpad(cardnum, 8, '0')         || lpad((select ssno                           from   emp                           where  id = empid), 8, '0') as prueba  from   events  where  eventid = 0         and eventid = 0         and machine in ( 11 )         and devid in ( 1, 2 )         and cardnum <> 0         and empid <> 0         and event_time_utc between to_date('2006-02-16', 'rrrr-mm-dd') and to_date('2007-02-09', 'rrrr-mm-dd') 	0.628469208116325
5726494	33212	mysql query help - multiple queries to same table	select c.poster, c.chattext, c.type, c.towho, c.timeposted, u.utype, u.locz     from chat c     left join users u on c.poster=u.name     where c.type!=4           or           (c.type=4 and c.towho='username')           or           (c.type=4 and c.poster='username') order by timeposted desc limit 0, 25 	0.217567015072167
5727039	1911	result that returns multiple groups based on id and date	select * from table as t1 where (select count(*) from table as t2        where t1.id = t2.id and t2.date > t1.date) < 3 order by id, date desc 	0
5733408	32635	how to modify values while extracting them from xml data in sql server	select  a.value('(id)[1]','int') as id, case    when a.value('(show/@pointer)[1]', 'varchar(5)') = 'yes' then '1'   else '0' end case as 'showitem', a.value('display[1]/@pointer[1]="display"', 'varchar(10)') as displaydetails,  a.value('displaydetails[1][@pointer[1]="display"]/detail1[1]', 'varchar(max)') as detail1 from    @xmlnode t cross apply t.doc.nodes(' 	0.000160682214665197
5735839	25239	mysql needed to join tables of grocery stores, upc codes, and prices	select itemlist.upccode as code, storetable.storecode as number from code itemlist left outer join pricelist p on itemlist.upccode = pricelist.upccode left outer join storenumber s on storetable.storenumber = pricelist.storenumber order by itemlist.upccode 	0.122396895112279
5743263	32413	using mysql count to count multiple columns	select name_of_follower,         count(name_of_follower)    from ( select name as name_of_follower            from abc           union all          select follower as name_of_follower             from abc        ) t  group by t.name_of_follower   order by count(name_of_follower) desc 	0.011051510738405
5744316	15618	mysql table becoming large	select * 	0.54254464695857
5762888	18096	sql server select column	select    e.name,    e.age from employee e 	0.15991665948501
5768936	12716	get the index of mysql result	select count(name) from mydb where score>(select score from mydb where name='andi') 	0.00955602912605173
5778182	5808	mysql different from	select * from theuser where userid=1233 and (active is null or active != 1) 	0.00841483439599622
5780639	18780	get articles and comments with only one sql query ? (one to many relation)	select * from articles as a inner join comments as c on a.articleid = c.articleid 	0
5781824	30739	php mysql_query - get row of current week with current date	select week from table_name where current_date() between start_date and end_date 	0
5782100	34626	can i select more counts in one query?	select type,        count(id) as count   from users  where type in ('1','2')  group by type 	0.0371319434974375
5810684	24787	select query to select unique combos	select distinct f2, f3, f4 from table; 	0.0439709533672191
5815209	98	how to use mysql count using joins?	select sc.name, count(*) as quotes from status_categories as sc inner join status_quotes as sq on sc._id = sq._category_id group by sc.name 	0.793193649891757
5836232	34519	mysql query to read out data in ip blocks?	select * from table where ip>=inet_aton('10.0.0.0') and ip<=inet_aton('10.0.255.255') 	0.549587693850184
5838975	25515	ruby on rails database entry matching, storage	select *,  if(color in ('green', 'red', blue', ...), 10, 0)  + if(size in (...), 10, 0)  + if(capacity in (...), 10, 0)  + if(origin in (...), 10, 0) as score from cars where color in ('green', 'red', blue', ...) or size in (...) or capacity in (...) or origin in (...) 	0.0878160842206458
5861623	914	mysql output hex string as utf-8	select convert(x'c3a9' using utf8) 	0.785004479909059
5862346	13902	combine two sql queries	select second.*, first.final_exam_level    from (your second query here) second             inner join         (your first query here) first    on first.technician_id = second.technician_id 	0.0415558590098314
5875293	32164	drop tables that are not in a list?	select concat('drop table ', table_name , ';') from information_schema.tables where table_schema='yourdatabase' and table_name not in ('table1', 'table2'); 	0.00552443632336244
5877582	18910	returning rows on a certain date in mysql	select * from tablename where date_format(timestamp,'%e %b %y') = 'date coming from php' 	0.000168971340733573
5893588	31406	query to find the size of data in a column	select * from tbl where datalength(rawdata) > 1048576 	0.000372149881317386
5903835	27407	get a count from a mysql inquire	select count(*) as numdrives      , concat(clients.name,' ',locations.name) as location    from drives   inner     join computers      on computers.computerid=drives.computerid     and drives.`size` > 5000  inner    join agentcomputerdata on computers.computerid=agentcomputerdata.computerid       inner    join locations      on locations.locationid=computers.locationid  inner     join clients      on clients.clientid=computers.clientid   where computers.computerid     not      in (select computerid from agentignore where agentid=0)   group     by concat(clients.name,' ',locations.name) 	0.00178114608936539
5904568	4248	how to get data and match with table variables?	select v_comments.v_comment_id, d_names.d_name, s_names.s_name,        v_comments.visit_reply, v_comments.just_date from v_comments left join d_names on v_comments.d_id = d_names.d_id  left join s_names on v_comments.s_id = s_names.s_id  where v_id = '$vid' and s_id='$sid' order by v_comments.id desc; 	0.00163074195686267
5909202	4123	retrieving two counts using a single sql statement	select    count(case status when 1 then 1 else null end) as ones,    count(case status when 0 then 1 else null end) as zeros from    mytable 	0.00453181775639826
5910766	3498	mysql query count	select * from friends where friend_id in (1,2,3,4) group by friend_id having count(friend_id) < 2 	0.356178943888014
5916014	24803	mysql, search a database and tell what tables contain two specific columns?	select *     from information_schema.columns    where column_name in ('columna', 'columnb') order by table_name, column_name 	0.00239751891667938
5916856	2755	cross joining a table on itself with count	select e.[event]     , sum( case             when s.[session time] between '2210-03-02' and '2210-03-05' then 1             else 0 end ) as precounter     , sum( case             when s.[session time] between '2210-04-02' and '2210-04-05' then 1             else 0 end ) as postcounter       , ed.[event description] from [shipcompanies].[dbo].mergedsessionsid as s     join [shipcompanies].dbo.eventsseparated as e         on s.id = e.id     join [shipcompanies].dbo.eventdescription as ed         on e.[event] = ed.[unique id] where s.company = 'superspaceshipone'     and (         s.[session time] between '2210-03-02' and '2210-03-05'         or s.[session time] between '2210-04-02' and '2210-04-05'         ) group by e.[event], ed.[event description] order by e.[event] 	0.0543395541979702
5921106	23438	multi table sql query	select   departure_time,   arrival_time,   depart.name,   arrive.name from trajects    inner join locations depart on (depart.location_id = trajects.departure_id)   inner join locations arrive on (arrive.location_id = trajects.arrival_id) 	0.31562780159854
5936061	2602	split the value in table column sql server 2008?	select substring(name,charindex('|',name, charindex('|', name)+1)+1,100) from  table1 	0.00208962622948
5942002	19135	what's the equivalent of php time() in mssql?	select datediff(ss, '1/1/1970 05:00:00', getutcdate()) 	0.643791737092474
5949727	12578	converting columns into rows using cursor	select id, fielda as field0 from tablea union all select id, fieldb from tablea union all select id, fieldc from tablea 	0.0122591216674104
5967469	23164	how to combine multiple rows in mssql	select t1.id     , stuff(         (         select ', ' + t2.address         from mytable as t2         where t2.id = t1.id         order by t2.address         for xml path(''), type         ).value('.', 'nvarchar(max)'), 1, 2, '') as address from mytable as t1 group by t1.id 	0.0058234115164811
5981595	24923	running a mysql query, storing a temp value, then running another query	select ... from ... where ... order by (prm_breedgender.breedgenderid = profiles.profilegenderid) desc 	0.0191546799268648
5983833	25986	left join with list of groups from one table, and flag from another	select g.name,        case when p.group_id is not null then 1 else 0 end as part_of_group     from groups g         left join permissions p             on g.id = p.group_id                 and p.user_id  = 60     order by part_of_group desc, g.name 	0
5984738	17483	total sales per month	select year(date) as salesyear,          month(date) as salesmonth,          sum(price) as totalsales     from sales group by year(date), month(date) order by year(date), month(date) 	0
5987868	22705	multipe group by, count and join	select   sum(t1.score) as totalscore,   sum(coalesce(t2.fouls, t3.fouls)) as totalfouls from table1 t1   left join table2 t2 on t2.name = t1.name   left join table3 t3 on t3.name = nullif(t1.name, t2.name) 	0.360261964323044
6005863	30424	how do i select a second column for the rows who have duplicates on the first column?	select a.city as city     from your_table a group by a.city   having count(a.country) = 1 union all  select concat(b.city, ', ', b.country) as city    from your_table b   where exists (select null                   from your_table c                  where c.city = b.city               group by c.city                 having count(c.country) > 1) order by city 	0
6008519	17032	convert from bit type to yes or no by query sql server 2005?	select     firstname,     lastname,     case when ismale = 1 then 'yes' else 'no' end as ismale from     members 	0.347292544718574
6016236	1701	sql union with order	select * from (select top 1 dbo.zerorates.maturity_date as date1, dbo.zerorates.zero_rate as rate1     from dbo.zerorates     where dbo.zerorates.maturity_date < '2013-05-16'     order by dbo.zerorates.maturity_date desc) as t union select * from (select top 1 dbo.zerorates.maturity_date as date2, dbo.zerorates.zero_rate as rate2     from dbo.zerorates     where dbo.zerorates.maturity_date > '2013-05-16'     order by dbo.zerorates.maturity_date asc) as t 	0.685509933826811
6029521	30449	how to select row from one of three tables based on fourth table that holds order of those entries from all three tables	select content_type, some_text, id as content_id from (                select 'content1' as content_type, content1.id, content1.some_text      union all select 'content2', content2.id, content2.some_text      union all select 'content3', content3.id, content3.some_text) contents join content_order   on content_order.content_type = contents.content_type  and content_order.content_id = contents.id order by content_order.id 	0
6036793	13753	sql: how to use union and order by a specific select?	select id from  (     select id from a      union all      select id from b  ) group by id order by count(id); 	0.12778626950766
6037444	40297	subquerying with a limit	select topics.id from   (select max(topics.posted) as date, categories.id as id   from topics, categories   where topics.category_id = categories.id   and ( categories.id in ( 1, 2, 3 )       or categories.parent in ( 1, 2, 3 ))   group by categories.id) t1 join topics  on topics.posted = t1.date and topics.category_id = ti.id 	0.347493466732078
6040455	17933	how to select just unique values into a mysql table based on the value in one column?	select * from x where column3 not in    (select column3 from x group by column3 having count(*) > 1) 	0
6042304	3460	select with un-standard group by in clause	select     * from     account where     idcustomernumber = '000001' order by     currency = 'usd'  desc   , currency   , accountnumber ; 	0.716244053171918
6049861	9050	difference in two row values of the same table	select * from ( select distinct visitlab.dateofentry, visitlab.labvalue, visitlab.code,      (lag(visitlab.labvalue) over (order by visitlab.dateofentry) - visitlab.labvalue) as diff from(xcx.patientvisit patientvisit inner join        xcx.masterpatient masterpatient        on (patientvisit.masterpatientid = masterpatient.masterpatientid)) inner join        xcx.visitlab visitlab        on (visitlab.masterpatientid = patientvisit.masterpatientid)        and (visitlab.visitnumber = patientvisit.visitnumber) where (masterpatient.masterpatientid = 'xxxxxxxx') and (visitlab.code = 'uqn0') and (patientvisit.dischargedate is null) and (patientvisit.facilitycode = 'x') ) inlineview where diff < .2 	0
6063190	8578	select rows with minimum difference	select    * from    table_a a    cross apply    (select top 1 number from table_b b order by abs(b.number - a.number)) b2 	0.00112753032172676
6076279	22283	mysql data from 3 tables	select * from messages  left join message_senders on messages.id = message_senders.message_id  left join message_recipients on messages.id = message_recipients.message_id  where message_senders.trashed = 1 or message_recipients.trashed = 1 and messages.user_id = <value> 	0.00465137462917298
6078556	25392	how to select all from sql query including subquery	select a.*     , name = case         when             a.name = 'a'          then 0          else 1     end as selected from points as a 	0.00980015929353785
6112596	36373	how do i update part of a composite primary key?	select source.delta,         source.vid,         target.delta,         target.vid  from   content_field_table source         inner join content_field_table target           on source.delta = target.delta  where  source.vid = '123'         and target.vid = '1234' 	0.00893970692947755
6118802	34178	mysql if record exists inside select query	select t.id, t.title, t.content, u.id, u.username, v.id from threads as t inner join users as u on t.userid = u.id left join votes as v on (v.userid = u.id and t.id = v.threadid) where (u.id = $userid) and (t.id = $threadid) 	0.167473091557987
6121775	31179	how can i visualise a histogram of timestamps (stored in mysql) without having to code much?	select date_format(click_date, '%y-%m-%d') as click_date,        count(*) as num_clicks from clicks where :start <= click_date and click_date < :end group by date_format(click_date, '%y-%m-%d') 	0.163457957248717
6127348	18993	keyword search engine that returns statistics instead of hits	select count(*) 	0.0944901854137291
6128990	38599	sql server datetime in 12am/pm format without the millisecond	select convert(varchar, getdate(), 101) +  replace(convert(varchar, getdate(), 0),replace(convert(varchar, getdate(),107), ',',''),'') 	0.147888268357903
6138786	1561	how to count null values from multi-columns	select mpan,        date,        sum           (             case when reading1 is null then 1 else 0 end +             case when reading2 is null then 1 else 0 end +             case when reading3 is null then 1 else 0 end           ) as nullcount from t group by mpan,          date 	0.0033246847889229
6139449	9296	sql - using a value in a nested select	select iteration,        col from tbl where id = 223652 and iteration = (select max(iteration) from tbl where id = 223652); 	0.194962019661625
6143975	20667	getting sql results in parts	select      col1,      col2  from  (      select           col1,           col2,           row_number() over (order by id) as rownum      from          mytable ) as myderivedtable where      myderivedtable.rownum between @startrow and @endrow 	0.0836478922121671
6169769	21693	group and count multiple fields at once	select ...  from   ads where  [search criteria] 	0.00120443856205045
6173301	32734	sql query using then(?) or a points system	select user.id, user.first, user.last,     if (user.first = q1 or user.first = q2, 1, 0) +     if (user.last = q1 or user.last = q2, 1, 0) as points from users as user order by points desc 	0.675253623680322
6175535	5925	mysql select query	select status,        count(*) as num,        group_concat(id) as ids from tests as status_stats union all select null as status,        count(*) as num,        group_concat(id) as ids from tests as total_stats 	0.387336905290878
6176077	14038	php join 2 tables by date problem	select * from (             select 1 as `table`, `col1` as `userid`, `col2` as `cat`, `col3` as `item_id`, `title` as `title`, etc... , `date` as `date` from `table1`             union             select 2 as `table`, `col1` as `userid`, `col2` as `cat`, `col3` as `item_id`, null as `title`, etc... , `date` as `date` from `table2`         ) as tb         order by `date` desc 	0.162318055645805
6190701	40515	number of times a record shows up : sql server	select numbers, count(*) as count from mytable group by numbers 	0.000421644956980048
6198559	11745	sql server - join on null values	select hl.*, hls.colorcode, hls.bold  from headerlinks hl left join headerlinkstyles hls on hl.linkid = hls.linkid order by row asc,[column] asc 	0.231401307816666
6208792	9605	select users who have not signed up for an interview	select users.* from users left join interviews     on users.id = interviews.id where interviews.id is null 	0.00974633469536666
6209645	3023	sql count totals within date ranges	select date(created_at) as created_at, sum(value) as total from changes where created_at >= curdate() - interval 30 day group by date(created_at); 	0.00264461830564527
6220238	4026	mysql: use set or lots of columns?	select from events where categoryx = true 	0.193469582306441
6233037	8455	sql statement which returns id and splits comma separated values	select nodeid,         s.part from #tmptable   cross apply [dbo].[splitstring](externalids, ',') as s 	0.000183222029782966
6235422	25281	using javamail to send email to users automatically on exceeding the due date	select user.email from studentaccount   user, issuebook rentals where  user.<id> = rentals.loginid  and   rentals.duedate < now   	0.00470190385140188
6242097	1831	convert float to datetime in oracle db	select to_date('12/30/1899', 'mm/dd/yyyy') + 40676.2641666667 from dual; 	0.100299661932763
6252327	20526	casting a concat	select 2 * 2; 	0.462114258016128
6255405	2356	what is the behavior for the minus operator between two datetimes in mysql?	select (20110413155959 - 20110413160000) as dates; 	0.729421635767347
6256173	8996	best method for transferring data between two sql databases	select * into targettable from [sourceserver].[sourcedatabase].[dbo].[sourcetable] 	0.140750694321242
6258585	8033	sql server query select 1 from each sub-group	select      *  from     (select         con,         owner,         method,         matrix,         result,         count,         rank() over(partition by con, owner, method,matrix order by result,count desc) as rnk     from #temptable ) a where rnk = 1 	0.00127071575040062
6262533	10002	sql group query with order by and limit	select * from (     (select *,         (select ttm from test.companies ic where ic.id = oc.id order by ttm desc limit 1) as maxttm         from test.companies oc where id = '2' order by ttm desc limit 2)     union     (select *,         (select ttm from test.companies ic where ic.id = oc.id order by ttm desc limit 1) as maxttm         from test.companies oc where id = '3' order by ttm desc limit 2) ) as myunion order by maxttm, id; 	0.738666853844991
6263453	9958	retrieve client ip address in mysql	select host from information_schema.processlist where id=connection_id(); 	0.0221118708078057
6272453	7745	mysql fulltext match against a list of keywords from a lookup table	select tbl.word, count(*) from (select * from input_form where match(title, story) against (word)) as tbl; 	0.00153775339329129
6280693	1363	mysql innodb table returns 20% of rows then halts	select eid, max(transdate) from subscribe group by eid 	0.000530186035360435
6285164	32869	can i combine two columns into one and then count values for them as if it were one column?	select t.completed_by, count(distinct t.unique_id) as rficount      from (select completed_by, unique_id               from rfi_                where date_submitted between '20110101' and '20110630'            union all           select assisting_analyst as completed_by, unique_id               from rfi_                where date_submitted between '20110101' and '20110630'                   and assisting_analyst is not null) t     group by t.completed_by 	0
6293916	39816	duplicate entries mysql with large data?	select   columna from     table group by columna having   count(*) > 1 	0.00145457996357179
6306110	37832	sql query get all categories and if are active	select  c.id                 ,c.name                 ,case                      when ic.categoryid is null then 0                     else 1                 end isactive     from    categories c left join items_categories ic          on ic.categoryid=c.id     and ic.itemid=@itemid 	7.49494367050595e-05
6312239	36204	joining 2 one to many relationships	select book.bookid, book.author, book.title, group_concat(category.categorydesc) from book join bookscategories on book.bookid = bookscategories.bookid join category on bookscategories.categoryid = category.categoryid group by book.book_id 	0.00255899126940368
6319411	17189	addition with multiple mysql entries	select l1+l2+l3+l4 as ltotal from table where id = '$sid' 	0.0188528510045852
6320238	29811	access database	select *, dateadd("d",5,startdate) as "5 days", dateadd("d",36,startdate) as "36 days" from processes 	0.427761135806762
6342809	40898	additional "or-criteria" in the on-clause of an inner join	select   ssn_in,   ssn_out,   coalesce(t1.ssn_number, t2.ssn_number) as ssn_number from   #rma1   left join #rma2 as t1 on #rma1.ssn_in = t1.ssn_number   left join #rma2 as t2 on #rma1.ssn_out = t2.ssn_number where   t1.ssn_number is not null or t2.ssn_number is not null 	0.51216312320698
6344731	36709	sql server: joining in rows via. comma separated field	select * into #order from (   select 1 orderid, 'ox101' ordernumber union select 2, 'ox102' ) x; select * into #orderitem from (   select 1 orderitemid, 1 orderid, '12,14,15' optioncodes   union   select 2, 1, '14'   union   select 3, 2, '15' ) x; select * into #option from (   select 12 optionid, 'batteries' description   union   select 14, 'gift wrap'   union   select 15, 'case' ) x; with n as (   select i.orderid, i.orderitemid, x.items optioncode   from #orderitem i cross apply dbo.split(optioncodes, ',') x ) select q.orderitemid, q.ordernumber,        convert(nvarchar(1000), (          select t.description + ','          from n inner join #option t on n.optioncode = t.optionid          where n.orderitemid = q.orderitemid          for xml path(''))        ) options from (   select n.orderitemid, o.ordernumber   from #order o inner join n on o.orderid = n.orderid   group by n.orderitemid, o.ordernumber) q drop table #order; drop table #orderitem; drop table #option; 	0.000121144477096575
6362328	40246	how do i recreate a view as a local table in sql server?	select * into newtablename from linkedserver.dbname.schemaname.view 	0.773795513834846
6377333	13723	oracle permission granting sql plus	select     p.grantee from     dba_tab_privs p where     p.privilege = 'execute'     and     p.owner = 'schema_name'     and     p.table_name in ( 'package_name', 'synonym_name' ) 	0.521924402176934
6379322	2517	mysql sum(), grouping by month, months with '0' don't appear	select mymonths.theyear, mymonths.themonth, coalesce(thedata.hours, 0) from mymonths left join (     select year(date) as theyear, monthname(date) as themonth, sum(block_time) as hours     from flights     where operator = 'psd'     group by year(date), monthname(date) ) thedata on mymonths.theyear = thedata.theyear and mymonths.themonth = thedata.themonth 	0.000196947453271472
6384372	9647	how can i nest a count within a sql query	select  sdtoken.iusernum,          chdefaultlogin,          datelastlogin,         count(*) as logincount from sduserscope      inner join sdtoken          on sduserscope.iusernum = sdtoken.iusernum             inner join sdlogentry                  on sdlogentry.chtokenserialnum = sdtoken.chserialnum                      inner join sdlogmessage                          on sdlogentry.imessagenum = sdlogmessage.imessagenum  where   sdtoken.iusernum = 17  and     sduserscope.isitenum = imysite  and     sdlogentry.dtgmtdate > gmtdatenow - 7 group by    sdtoken.iusernum,              chdefaultlogin,              datelastlogin 	0.502331193042963
6388235	27979	sql date conversion	select convert(varchar,cast(date_of_hire as datetime) ,101) as date_of_hire from employee where employeeid='input' 	0.260603860546877
6407935	8481	sql help - counting rows from two tables	select `name`, count(*) as `size` from products right join category on category.`id` = products.`categoryid` group by category.`name` 	0.00236434440780343
6421499	13788	in sql how to return records matching date and month only (ignore year)	select * from table where to_char(month_column,'mm/dd') = '06/21' 	0
6425553	29690	sql query results to be displayed in the order of the manually provided values	select cardnumber, first_name || ' ' || last_name  from (      select cardnumber, first_name, last_name, c.orderno      from cardholder ch, (select '%1111%' cardmask, 1 orderno from dual                         union all                         select '%2222%', 2 orderno from dual                         union all                         select '%3333%', 3 orderno from dual                         ) c      where ch.cardnumber like c.cardmask      order by c.orderno ) t 	0.0360812289531128
6425684	2647	t-sql use table variable or sum against parent table	select   stuff,    sum(case when daydiff <= 90 then somevalue else 0 end) as sumvalue90,    sum(case when daydiff <= 60 then somevalue else 0 end) as sumvalue60,    sum(case when daydiff <= 30 then somevalue else 0 end) as sumvalue30 from    (     select       stuff,        datediff(day, somedata, getdate()) as daydiff     from       mytable     where        ...     ) foo group by    ... 	0.0719389343844451
6425789	27037	sql return transaction table with the date of previous payment	select transid, tenantid, transactiontype, amount, transactiondate,        (select max(i.transactiondate)         from unnamed_table i         where i.transactiondate < o.transactiondate           and i.transactiontype = 2           and i.tenantid = o.tenantid) prevtransdate from unnamed_table o 	0.000202839426424015
6437853	14313	find highest value in row and echo number and column name	select  id,  greatest(one, two, three, four, five) value,         case greatest(one, two, three, four, five)          when one then 'one'          when two then 'two'          when three then 'three'          when four then 'four'          when five then 'five' end column_name  from your_table 	0
6439370	3571	how do i get the number of members on status name	select count(*) from member inner join mmship    on member.member_id = mmship.member_id    inner join mshipstatus    on mshipstatus.mshipstatus_id = mmship.mshipstatus_id where mshipstatus.mshipstatusname = 'prospective'    and month(mmship.mmshipstart_date) = month(getdate()) 	0
6441080	3845	sql group by query - get related fields of aggregate function	select t.id, t.time, t.distance, t.price from table t join (select min(time) as min_time, distance         from table         group by distance) as tmp       on (t.distance = tmp.distance and t.time = tmp.min_time) where t.distance in (500, 1000) 	0.0527100983646102
6447380	14785	same query mysql user defined variables	select   total from   (select (some really taxing calculation) as total, * from purchases) as purchases where total < 55 and itemname = "bananas"    or total > 90 and itemname = "apples"    or total = 30 and itemname = "peaches" order by   total 	0.0514712870721674
6457737	30895	mysql associated table count() and group by	select  ads_cate.catename, count(ads_list.id), from ads_cate inner join  ads_list on ads_cate.id = ads_list.category group by catename  order by catename 	0.010716409928425
6502526	12650	simple sql query..cannot get it resolved	select count(*) from enemies where not exists (select * from weapons where weapons.redid=enemies.id) 	0.590428213649985
6513332	24648	mysql views cannot have subquery in from, and don't maintain order. how can i create a view from this query?	select     appointment.employee_id ,     ( select title.`name`       from appointment_title         inner join title           on appointment_title.title_id = title.id       where appointment.id = appointment_title.appointment_id       order by appointment_title.effective_date desc       limit 1     ) as title_name from appointment group by appointment.employee_id 	0.373613017361957
6515252	10368	selecting records from mysql table that were created in the last 24 hours via timestamp type	select * from list where timestamp > date_sub(now(), interval 1 day) 	0
6519289	25781	how to add a column based on certain date range with type	select st.*, ft.rate from second_table st left join first_table ft      on ft.type=1 and month(acct_date) = month(eff_date) and year(acct_date) = year(eff_date) 	0
6526252	6138	query with sql datepart	select     max(serial_number),     convert(date, dateofappointment) as [day] from     #tempserialsbydate group by     convert(date, dateofappointment) 	0.771636032507303
6537796	27848	sql filtering on values	select    userid, operationid,   sum(case category when 'major' then 1 else null end) majorfaults,   sum(case category when 'minor' then 1 else null end) minorfaults,   date from yourtable group by userid, operationid, date 	0.0523805722172534
6548965	38688	sql sub and grand total	select loguser,logdate,logaction,sum(logtime) from log where loguser in ('scott')   and logdate   between '2011-06-01' and '2011-06-15' group by loguser,logdate,logaction with rollup order by logdate desc 	0.0285982197170607
6551602	9352	how to make sql more efficient. need just the count	select    count(user.id)  from    users  where    (select count(fans.id) from fans where user_id = users.id) > 0 	0.394589199029065
6552156	39625	full text view not return result	select * from vwpersonsearch  where contains([full name],'"mark*" and "rush"') 	0.588242290725991
6559428	8558	selecting all orders for last 30 days, and counting how many per day	select count(*) as orders, date_field from your_table where customer_id=$my_cusotmer group by extract(day from date_field) 	0
6569376	13864	best way to interpolate values in sql	select case when next.date is null  then prev.rate             when prev.date is null  then next.rate             when next.date = prev.date  then prev.rate               else ( datediff(d, prev.date, @inputdate) * next.rate                     + datediff(d, @inputdate, next.date) * prev.rate                    ) / datediff(d, prev.date, next.date)        end as interpolationrate  from   ( select top 1          date, rate      from rates     where date <= @inputdate     order by date desc   ) as prev   cross join   ( select top 1          date, rate      from rates     where date >= @inputdate     order by date asc   ) as next 	0.31416784106622
6571019	35034	combining maths queries mysql	select -(select sum(amt) u from entry where en_type='some_type' and num='some_num')        + (select sum(amt) v from entry where en_type='some_type' and num='some_num')        + (select abal x from accounts where num='the_same_num_as_above') as y; 	0.518181902267853
6589514	17835	use triggers to keep history of relational tables	select @trans_id=transaction_id from sys.dm_tran_current_transaction 	0.11766007568654
6597792	3227	select data from one view and use that to select from another view	select b.*     from viewa a         inner join viewb b             on a.commonid = b.commonid     where a.otherid = xxx 	0
6602343	18142	how to show rows with zero counts in mysql group by query?	select count(t.longname) as cnt, l.location  from locations l    left join topics t     on  t.longname = l.longname     and t.tag = 'atag'       where l.location in ('japan', 'france', 'italy')  group by l.location  order by field(l.location, 'japan', 'france', 'italy') 	0.00257275505375224
6607159	14797	pl/sql null value problem in query	select * from tablea where (col1 = parameter1 or parameter1  is null) and (col2 = parameter2 or parameter2  is null) and (col3 = parameter3 or parameter3  is null) 	0.704888258437075
6616207	36585	oracle timestamp difference greater than x hours/days/months	select (actionendtime - actionstarttime) actionduration   from actiontable  where actionendtime - actionstarttime > interval '1' hour 	0.000721879185145764
6618159	33826	oracle - how to calculate profit that is above average	select * from tbl where sellprice-buyprice > (select avg(sellprice-buyprice) from tbl ) 	0.001203046453793
6623940	25814	find and group duplicates	select  a.names name,         b.names dupe_name,         count(*) num_dupes from    names_tbl a, names_tbl b, md5_tbl md5a, md5_tbl md5b where   a.id < b.id and     a.id = md5a.id and     b.id = md5b.id and     md5a.md5 = md5b.md5 group by a.names, b.names order by a.names 	0.0343218196962294
6624957	2309	sql: select if entry in one column corresponds to another column of a different table	select distinct n.node_name, n.data     from nodes n         inner join nodeactivity na             on n.node_name = na.node_name                 and na.time = '00:00:00' 	0
6628027	3968	grab associated options from another table and merge with current results	select options.name from sites inner join assoc on sites.id = assoc.site_id inner join options on options.id = assoc.assoc_id where assoc.type = 'options' 	0
6643357	18188	sqlite, identify empty nonnull cells	select myid from mytable where trim(myid) = '' 	0.0180683936895022
6644702	21662	sql query for counting values in a set column	select count(nullif(columnname & 1,0)) as count1stval,        count(nullif(columnname & 2,0)) as count2ndval,        count(nullif(columnname & 4,0)) as count3rdval,        count(nullif(columnname & 8,0)) as count4thval, 	0.00608495626146161
6644962	8336	what's more efficient? a number of sql queries or looping through them all?	select sum(case               when t.time between beginningday1 and endday1 then 1              else 0            end) as num_day1,        sum(case               when t.time between beginningday2 and endday2 then 1              else 0            end) as num_day2   from your_table t 	0.00262243319453962
6674682	5032	group by in db2	select d.user_id, d.appointment_id, d.date      from doctors_appointment as d     join (select user_id, min(date) as apt_date             from doctors_appointment             where date > current_timestamp               and user_id in (23, 24, 25)            group by user_id) as t        on t.user_id = d.user_id and t.apt_date = d.date; 	0.364686151285644
6680568	39400	sql: select most recent date for each category	select     category_a,     category_b,     max(date) from     some_unnamed_table group by     category_a,     category_b order by     category_a,     category_b 	0
6685899	6272	oracle sql: how to select n records for each "group" / "cluster"	select * from  (     select       bt.col_a,       bt.col_b,       bt.process_type_cod,       row_number() over ( partition by process_type_cod order by col_a nulls last ) rank     from small_table st     inner join big_table bt       on st.process_type_cod = bt.process_type_cod ) where rank < 11 ; 	5.1423803635628e-05
6685904	35813	get coordinates (row,column) of a table in a mysql query	select name,  case col   when 0 then col_0   when 1 then col_1 end as rowcol from tbl1 as t1 inner join tbl2 as t2 on t1.row = t2.row 	0.0446282884010989
6686665	33303	query relation table against another column	select distinct entity_id from construction  where entity_id not in (     select entity_id from construction c left outer join available a on a.id = c.component_id      where a.id is null  ); 	0.00564587478349863
6701160	15108	mysql correlated subquery count across tables	select f.f_id, (select count(t.t_id)                  from topics t                 where t.f_id =  f.f_id) as tc,                  count(distinct p.p_id) as pc from forums f join topics t on t.f_id = f.f_id join posts p on p.t_id = t.t_id where f.f_id = 78 group by f.f_id; 	0.663171892840417
6718396	5384	user experience count	select uid, sum(positive - negative) as netexp from experience  group by uid 	0.100069649054545
6723355	6480	sqlite timestamp in where clause	select sum(price) as total from ticketline where dateregistered > datetime('2011-07-16 17:00:00') 	0.510012690275035
6741958	20148	t-sql: how to return parent and child records in a certain format?	select parentname, childname, childfield1, childfield2 from   (select pt.parentid, 0 childid, pt.parentname, '' childname, '' childfield1, '' childfield2    from parenttable pt    union   select ct.parentid, ct.childid, '   ' parentname, ct.childname, ct.childfield1, ct.childfield2   from childtable ct) order by parentid, childid 	0
6760253	20034	how to output data from several tables order by create_time all together	select 'post' as type      , p.post_id as id      , p.author      , p.create_time from tbl_post as p where author = 42 union all select 'article' as type      , a.article_id as id      , a.author      , a.create_time from tbl_article as a where author = 42 union all select 'photo' as type      , ph.photo_id as id      , ph.author      , ph.create_time from tbl_photo as ph where author = 42 union all select 'comment' as type      , c.comment_id as id      , c.author      , c.create_time from tbl_comment as c where author = 42 order by create_time 	0.000250166650560494
6773327	15436	sqlite order by 3 fields and return top 1 for each category	select * from captures_table as c1 where (100*pounds+10*ounces+drams) =        (select max(100*pounds+10*ounces+drams)        from captures_table as c2       where c2.species=c1.species) order by pounds desc, ounces desc, drams desc 	0
6800732	25960	joining multiple entries to single entry	select prop.*, group_concat(filenames) as files    from properties prop     join images on prop.id = images.prop_id    where prop.owner_id = 'something'    group by prop.id 	0
6822651	34448	postgresql order by values in in() clause	select * from (   select distinct id    from items    where id in (5,2,9)  ) t order by  case id   when 5 then 1    when 2 then 2   when 9 then 3  end 	0.39497880281559
6822827	4346	how to count up to certain number of rows e.g. if exceeds 1,000, then select count only up to 1,000?	select count(*) from ( select 1 from t limit 1000 ) a 	0
6826614	14769	how can i search for rows that contain a non-alphanumeric or space character?	select * from mytable where myfield like '%[^a-za-z0-9 ]%' 	0.0376041261505361
6828369	8307	display two different columns from two different tables with order by	select distinct varwineprice  from `tbl_wines`  union  select distinct varprice  from tbl_price order by varwineprice 	0
6828978	18816	mysql multiple date subqueries	select        date_format(dateadd, '%y-%m-%d'),       sum( if( compid = 132, 1, 0 ) ) as count132,       sum( if( compid = 149, 1, 0 ) ) as count149    from       atable     where           elemname = "anelement"       and ( compid = 132 or compid = 149 )       and dateadd between "2010-09-01 00:00:00" and "2010-10-26 23:59:59"    group by       dateadd 	0.281447297363468
6835922	35229	grouping columns in pivot query	select *      from (      select      year(orderdate) [year],      case when month(orderdate)<=3 then '1-3'           when month(orderdate)<=5 then '4-5',           when month(orderdate)<=10 then '6-10',           else '11-12' end [monthrange]      subtotal     from sales.salesorderheader      ) tabledate      pivot (      sum(subtotal)      for [monthrange] in (       ['1-3'],['4-5'],['6-10'],['11-12']      )     ) pivottable 	0.163301711983144
6841812	40243	how to find the last row in a column with duplicate values	select t.*  from  (     select userid, max(rownumber) m      from table     group by userid ) c     inner join table t          on c.userid = t.userid and c.m = t.rownumber 	0
6854203	2255	sql query: extract rows having specific course only	select appid from #app a where  appid in (select appid from #app where course='c++') and 1 = (select count(course) from #app where appid=a.appid) 	0.000351491760154737
6862519	13359	sql query for filtering data with where clause on same column	select distinct a.title, a.id from a where     a.id in (select distinct b.title_id from b where b.tag_id='16')     and a.id in (select distinct b.title_id from b where b.tag_id='26') 	0.106146496749423
6864727	20146	using sqlite orderby field	select * from timerecordtable order by timeindb desc 	0.359839939977593
6866768	24403	get mysql unique key combos	select constraint_name, group_concat(column_name order by ordinal_position) as cols from information_schema.key_column_usage where table_schema = 'db_name' and table_name = 'table_name' group by constraint_name 	0.00247418116320031
6877307	27182	mysql, php , how to count results that are the same?	select   talentnum,   page_name,   count(*) as cnt from findme group by talentnum, page_name order by cnt desc 	0.00042111461813851
6892264	35487	php mysql select query	select users.id, users.store, retail.id, retail.store from retail join users on users.id=retail.store 	0.39914744212743
6893750	21580	mysql random record with a bias	select * from ( select * from abc where b.points > 75 order by rand() limit 5 cross join  select * from abc where b.points > 50 and b.points <75 order by rand() limit 3 cross join  select * from abc where b.points > 25 and b.points <50 order by rand() limit 2 cross join  select * from abc where b.points > 0 and b.points <25 order by rand() limit 1 ) as result order by rand() limit 3 	0.0131480019249285
6894319	632	sqlite from clause select statement	select * from     (         select totable         from rdsynchronisationcontrolheader          where fromtable ='rd.transactioncontrol'     ) 	0.492017813851039
6896360	31197	mysql select destinct with two tables and by timestamp	select t1.id, t1.unitid, t2.maxtime, t1.info from info t1 inner join (select unitid, max(time) as maxtime              from info             group by unitid) as t2 on (t1.unitd = t2.unitid and t1.time = t2.maxtime) 	0.00430230369160129
6898624	6723	count data in specific row on mysql table	select sum(stores) from tablename 	0.000274622180437203
6903320	7012	mysql select question	select * from certain_table where created_at > now() - interval 2 day and certain_column = 'certain word'; 	0.764170900985442
6904037	6162	multiple table joins	select c.customerid, c.customeractive, c.protected, f.frequencytype from customers c    join customerservice s       on c.customerid = s.customerid    join frequency f       on s.frequencytypeid = f.frequencytypeid 	0.268566026835627
6919851	5067	create a user friendly drop down while retaining original column value?	select    userid,     isnull(lname,'') + ', ' + isnull(fname,'') + ' (' + isnull(userid,'') + ') '            as fullname  from    user order by    fullname 	0.00331700945311163
6935707	26709	count another count value but only if it is high enough	select   count(case when total >= 75 and `1month`   > 10 then name end) as `10+ per month count`,   count(case when total >= 75 and `1quarter` > 10 then name end) as `10+ per quarter count` from (   select d.name,      count(distinct case when a.created > date_sub(now(), interval 1 month) then a.id end) as `1month`,      count(distinct case when a.created > date_sub(now(), interval 3 month) then a.id end) as `1quarter`,      count(distinct a.id) as total   from dr d     join answer a on a.dr_id=d.id and a.status=3   group by d.id ) s 	0.00208833338734341
6955726	14256	mysql get unique key while selecting	select uuid(),name from( select name from talbe1 union all select name from table2) 	0.000270380261864358
6963106	31351	query for getting the first entered field for every user	select   u1.user_id,   u2.first_entry_weight,   u1.weight             as last_entry_weight from daily_measurements u1   inner join (select                 u1.user_id,                 u1.weight              as first_entry_weight,                 u2.fe,                 u2.le               from daily_measurements u1                 inner join (select                               daily_measurements.user_id,                               min(date_entry)            fe,                               max(date_entry)            le                             from daily_measurements                             group by daily_measurements.user_id) u2                   on u1.user_id = u2.user_id                     and u1.date_entry = u2.fe) u2     on u1.user_id = u2.user_id       and u1.date_entry = u2.le 	0
6968248	17608	return multiple semi-identical rows with specifics differences	select  yt.id ,       num.number as date_reference ,       yt.identical_value from    yourtable yt join    numbertable num on      num.number between yt.date_start and yt.date_end 	0.00673033080455338
6971915	4973	most popular mysql row over last 7 days	select l.page_id, p.description, count(l.id) from loaded_page l  inner join page p on p.id = l.page_id where l.date > :sevendaysago  group by l.page_id, p.description order by count(l.id) desc 	0
6978268	11324	how do i only pull the top "x" rows from a table?	select * from tw order by time desc limit 8 	0
6988378	13773	sql - correctly use constants instead of table name in from clause	select exp(sum(log(num))) as product from (select 2        union all       select 3       union all       select 5       union all       select 7       union all       select 11       union all       select 13) as nums(num) 	0.52216227422118
7009652	10166	sql monthly summary	select a.month, isnull(b.countvalue,0) count from (select 1 as month union  select 2  union  select 3  union  select 4  union  select 5  union  select 6  union  select 7  union  select 8  union  select 9  union  select 10  union  select 11  union  select 12 ) a left join (select datepart(month,startdate) as month, count(id) as countvalue from yourtable group by datepart(month,startdate))b on a.month = b.month 	0.0571868974349104
7012841	17068	how to use inner join to get username from one table by the id stored in another	select j.title, u.username from jobs j left join users u on u.id=j.added_by 	0
7027007	9652	transpose column result in resultset to rows	select continent, group_concat(county order by country) as countries  from tablexxx group by continent order by continent 	0.0012229234953625
7033179	40455	mysql possition of row by order	select count(*) + 1 as 'position' from table where points >     ( select points from table where id = someidhere ) 	0.0156405299896734
7042677	12225	sql - extracting ordid having item = "tent" only	select id, ordid, item from yourtable where item = 'tent'   and ordid not in (select distinct ordid                      from yourtable                     where item <> 'tent') 	0.00103062494498111
7045843	7134	grouping amounts of data together and creating a on-the-fly amt column	select join_id, bool, count(id) as amount from mytable group by join_id,bool 	0.0222460882044075
7072687	38223	mysql time fields, checking boundaries/inclusion	select * from `available_table` where ( time(now()) > `begin_time` and time(now()) < `end_time` ) 	0.0483231796982717
7079822	39196	return rows which don't have any matches in multiple-join situation	select b.tourrefcode, t.startdate, sum(a.adults + a.children + a.infants) as pax from  explorer.booking_record b inner join explorer.bookingroom a on a.bookingref = b.bookingref right join explorer.tour t on b.tourrefcode = t.tourcode and (t.startdate > '2012-02-01' and t.startdate < '2012-03-01') and (b.bookingstatus = "p" or b.bookingstatus = "f") and (b.tourdeparturedate > '2012-02-01' and b.tourdeparturedate < '2012-03-01') group by t.tourcode having sum(a.adults + a.children + a.infants) < 120 	0.00174522627905547
7086721	352	multiple sql select	select * from table1,      table2 where table1.date = 'somedate'   and table2.date = 'somedate' 	0.195265103588075
7092208	26465	how to write the select query to calculating difference of 2 timestamp fields in oracle 10g based on condition	select nvl(date_of_notification, systimestamp) - date_of_loss from the_table; 	0
7127092	11891	join info from one table onto a union of two others... is it possible?	select *   from products as p where  exists(select * from cat_index1 as c1 where p.pid = c1.cid) or  exists(select * cat_index_2 as c2   where p.pid = c2.cid) 	0.000124347199555797
7131331	18483	get second largest mark from mysql table	select distinct   name, mark from   stud  where   mark = (select max(mark) from stud where mark < (select max(mark) from stud)) order by   name 	0
7133942	7754	returning all values in another table that matches one linked value in another	select c.car, m.model_id, m.model from models m inner join cars c on c.car_id = m.car_id where m.car_id = (select car_id from models where model = 'escort'); 	0
7145829	38341	how to get row count in all rows?	select id, (select count(*) from table) as totalrows from table; 	0
7145890	9507	mysql: grouping results	select site_id, (sum(wky) + (sum(earnings) / 0.75))  from earnings_date where earnings_date between '2011-08-14' and '2011-08-16' group by site_id 	0.217444685996296
7145919	29618	php mysql, union tables	select *, 'job' as origin          from job         where status!=2           and status!=3 union select *, 'emp' as origin         from emp         where status!=2           and status!=3     order by (id/popularity) desc         limit {$from},$vpc 	0.242120549565341
7162047	6629	check if timestamp is after 12 hours	select * from table where creation > unix_timestamp() + 43200 	0.000477582476568428
7165128	12419	mysql: how to read a table from one database while searching second database table per each row?	select t1.*, t2.* from database1.table1 t1 left outer join database2.table2 t2 on t1.id = t2.id 	0
7166034	20808	list of views referencing a table	select *  from information_schema.views  where view_definition like '%abc%' 	0.0103113187220069
7176934	6705	select with multiple tags	select     content.id,     content_text.content from content inner join tags_to_content t1 on     t1.content_id = content.id inner join tags_to_content t2 on     t2.content_id = content.id where t1.tag_id = 1 and t2.tag_id = 2 	0.0439548858996652
7185313	10561	summing multiple columns	select userid, sum(points_a) + sum(points_b) as total from entry group by userid 	0.0147686189670147
7215032	35226	order by based on entered keyword	select  * from    subject sm where   sm.subjectname like '%' + @subjectname + '%' order by case when sm.subjectname = @subjectname then 0               else 1          end asc ,         sm.subjectname desc 	0.0116593286640966
7230116	38891	returning last inserted id from mysql	select last_insert_id(); 	0
7233703	12970	how do i find out which tables have no indexes in mysql	select * from information_schema.tables where table_schema = 'your_database' and table_name not in  ( select  table_name  from ( select  table_name, index_name from information_schema.statistics  where table_schema = 'your_database' group by  table_name, index_name) tab_ind_cols group by table_name ) 	0.0034020371862068
7235323	20770	pull column twice from same table without subquery	select a.*, b.head as nullhead from pages a, pages b where a.id in ( '$id1', '$id2' ) and b.id = '0' 	0.000207330956469412
7239943	40365	suppress ora-01403: no data found excpetion	select nvl(balance,0)  into v_balance from  (     select sum(nvl(book_value,0)) as balance     from account_details     where currency = 'ugx' ); 	0.0757511674163072
7263003	26514	sql make a query with new column values depending on fixed values	select a,id      , a.name      , b.risk  from table1 as a   join table2 as b     on b.value = ( select max(bm.value)                    from table2 as bm                    where bm.value <= a.value                  ) order by a.value desc 	5.71330600006431e-05
7275649	14168	mysql: how to count from columns separately?	select count(ssn) as patient_count, 'ssn' as count_type from patients where ssn="0000000000000000"; union select count(firstname) as patient_count, 'firstname' as count_type from patients where firstname="0000000000000000" union select count(lastname) as patient_count, 'lastname' as count_type from patients where lastname="0000000000000000" 	0.00464532827560617
7276766	35303	select the same column multiple times (sql server)	select projectname, st.name as statusname, pr.name as priorityname     from projects p      left join statuspriority st on p.statusid = st.id      left join statuspriority pr on p.priorityid = pr.id 	0.000722068734638254
7280363	17231	views are rewritten when i save	select load_file(concat(@@global.datadir, 'tablename/viewname.frm')); 	0.782698630546979
7289775	4396	how to order by most results in mysql?	select author_id, count(*) as posts_count from posts  where status = "live" and author_id not in(0,1) group by author_id order by posts_count desc; 	0.0209045760601327
7290032	32801	sql server: is it possible to union two tables in a select statement without using a temp table?	select max(permissionid) from (select @contactpermission as permissionid union all       select @grouppermission as permissionid) as t 	0.174904673168192
7301497	12259	select only newest grouped entries	select *  from mytable mt      join ( select max(timestamp) as max, event             from mytable             group by event) m_mt      on (mt.timestamp = m_mt.max and mt.event = m_mt.event); 	0
7302244	7711	how can i select data from 3 tables in sql?	select username, productname, review   from user a inner join product_review pr     on a.user_id = pr.user_id inner join product p     on p.product_id = pr.product_id  where a.user_id = 1 	0.00346386955567046
7302441	36177	sql get the products with more attributes in common with another product	select a1.prod_id,p.name,count(*) as num_attr_in_common from attr_rel as a1 inner join ( select attr_id from attr_rel where prod_id = 3) as a2 on a1.attr_id = a2.attr_id and a1.prod_id <> 3 inner join products as p on p.id = a1.prod_id group by a1.prod_id order by num_attr_in_common desc 	0
7307773	23394	comparing three fields	select * from mytable where city like '%$xyz%' or name like '%$xyz%' or country like '%$xyz%' 	0.0291681033342797
7308373	31472	multiple mysql joins	select l.img_id, l.img_name,   (select count(*) from tbl_comments c where i.img_id = c.img_id ) as comment_count,  (select count(*) from tbl_vote v where i.img_id = v.img_id ) as vote_count from tbl_images i 	0.608318987636099
7309826	29642	how to retrieve records filtering by day and month in mysql?	select * from table where month(birthday) = month(current_date) and day(birthday) = day(current_date)     	0
7318207	37787	dependent with clauses in oracle reports	select x, y   from         (select 1 as x           from dual) abc,        (select 2 as y           from dual) def 	0.716208524925961
7328013	2868	using group by in mysql while using distinct on another column	select  `clicks_region`, count(*) as total   from      (select distinct 'clicks_region', 'clicks_ip'       from 'clicks'      where `clicks_to_websites_id` = '1'       and date(`clicks_date`) = date('2011-08-30' )) x  group by `clicks_region` 	0.00861064926442768
7330561	7978	convert mssql datetime to mysql datetime	select date_format( str_to_date('feb 23 2011 9:00am', '%b %d %y %l:%i%p'), '%y-%m-%d %h:%i:%s' ); 	0.0915108957819532
7344824	34261	how can i group by more than one row/column?	select product,  sum(case when month(date) =  1 then 1 else 0 end) jan,  sum(case when month(date) =  2 then 1 else 0 end) feb,  sum(case when month(date) =  3 then 1 else 0 end) mar,  sum(case when month(date) =  4 then 1 else 0 end) apr,  sum(case when month(date) =  5 then 1 else 0 end) may,  sum(case when month(date) =  6 then 1 else 0 end) jun,  sum(case when month(date) =  7 then 1 else 0 end) jul,  sum(case when month(date) =  8 then 1 else 0 end) aug,  sum(case when month(date) =  9 then 1 else 0 end) sep,  sum(case when month(date) = 10 then 1 else 0 end) oct,  sum(case when month(date) = 11 then 1 else 0 end) nov,  sum(case when month(date) = 12 then 1 else 0 end) dec,  count(date) total from   mytable group by   product 	0.0728904347492625
7351569	38727	remove or replace with blank partial string in mysql query	select replace(replace(ot.title, 'free', ''), '&nbsp;<br>', ' ')     from orders_total as ot; 	0.247117986523478
7355554	14684	combine two result sets and still keep one of the columns unique	select coalesce(set2.id, set1.id) as id,        case when set2.id is null then set1.value else set2.value end as value from set1     full join set2         on set1.id = set2.id 	0
7356830	36240	mysql selection preference	select * from advert order by rand() * (some magical preference ordering) desc limit 3 	0.480610595177605
7357955	34944	sql server set digit	select right('00000' + cast(column_name as varchar(5)), 5) as my_column from table_name 	0.190074064989651
7360666	26203	how to rounded to the lowest multiple of 5 in sql server 2008?	select floor(49/5) * 5,  floor(54/5) * 5 	0.00403965417461008
7397608	38702	how to find the grant permission for objects from user schema	select * from   all_tab_privs where  grantor = 'db1owner' and    grantee = 'db1user' 	0.0031389394006529
7399460	34594	sql query to transform a list of numbers into 2 columns	select first.id, min(second.id) as next_id from table_name first, table_name second where first.id < second.id group by first.id 	0
7406299	33396	replicate the value get in a sql select	select     field1,     field2,     custom_field1,     custom_field1 as custom_field2     from     (     select       field1,       field2,       case when field3 <> field4        then case when substring(field10,1,3) = field5          then (field1 * field3) + field4          else (field1 / field3) + field4          end         end as custom_field1      from table ) as sub 	0.0117009972636739
7409435	22098	find number of rows in a table	select count(*) as length from tablename 	0
7422486	10578	sql-query to find similar fields	select    a.id  from    table as a join table as b    on a.a_1 = b.a_1 and ... and a.a_j <> b.a_j 	0.0242275376079945
7437138	11696	how to get a master table record by count of detail table records without top(1)	select t.name from team as t join teammember as tm on tm.teamid = t.id group by t.name having count(tm.id) = (select max(members) from (select count(id) members from teammember group by teamid) as sub) 	0
7438356	23576	database query vs. programming language to check for occurence in data	select firstname, lastname from employee;  firstname | lastname   fred      | bloggs  joe       | citizen  bill      | citizen  andrew    | smith select case when (select count(*) from employee e where e.lastname=e2.lastname) > 1 then substr(firstname, 1, 1) || '. ' else '' end || lastname from employee e2;   ?column?    bloggs  j. citizen  b. citizen  smith 	0.568963939689484
7444846	38642	business days calculation	select  datediff(day,dateadd(day,-1,startdate),isnull(enddate,getdate())) -  ( case when datename(dw, startdate) = 'sunday' or  datename(dw,isnull(enddate,getdate())) = 'sunday' then 1 else 0 end) - ( case when datename(dw, startdate) = 'saturday' or       datename(dw,isnull(enddate,getdate())) = 'saturday' then 1 else 0 end) numberofdays          from <mytable> 	0.0167295676544637
7456693	10697	sql left join but don't want all records in the left table	select proj.id, proj.priority, proj.status, proj.projectname,  status_tmp.statusdate,     status_tmp.statusdetail from proj  left join (select s1.* from projectstatus as s1 left join projectstatus as s2 on s1.statusproj = s2.statusproj and s1.statusdate < s2.statusdate where s2.statusproj is null ) as status_tmp on (proj.id=status_tmp.statusproj) where proj.priority='high' and proj.status!='cancelled' and  proj.status!='completed' and  (status_tmp.statusdate < date_sub(curdate(),interval 14 day) or  status_tmp.statusdate is null ) 	0.00819258298593368
7464313	25810	how to query sum field on mysql by month	select  month(mydate),  phone,  name,  sum(costa),  sum(costb)  from mytable  where month(mydate) = '9'  group by month(mydate), phone, name 	0.00106735461288522
7467311	19635	combination of columns in where condition	select * from employees where employee_firstname = @emp_firstname   and employee_lastname  = @emp_lastname 	0.011606358112887
7478777	10081	how do i format datetime in mysql?	select date_format(new_ts, "%m/%d/%y %l:%i %p") 	0.105724982571875
7482194	14327	sql group by a substring in a field	select substring(cityname, charindex('(',cityname)+1,(len(cityname) - charindex('(',cityname)-1)) from cities where cityname like '(%)%' 	0.0904183679562904
7503220	35483	join row with max row in another table?	select * from auctions a inner join  (     select * from auction_bids x     inner join     (         select auction_id, max(bid_amount) as winner         from auction_bids         group by auction_id     ) y     on x.auction_id = y.auction_id     and x.bid_amount = y.winner ) b on a.auction_id = b.auction_id 	0.000236117733733231
7507956	7984	join mysql query, two of the same column names, how to display data?	select wp_posts.id as wpp_id, wp_users.id as wpu_id 	0
7512028	8374	sql find name doubles and sum values	select   user_name,          sum(hours) from     your_table group by user_name; 	0.00349496330371418
7545795	715	how to select multiple columns without duplicates in one column in oracle	select s_id        , c_id        , min_order_id        , no_of_orders from (     select s_id            , c_id            , min_order_id            , no_of_orders            , rank() over (partition by s_id                            order by no_of_orders desc, min_order_id asc) rnk     from (         select s.s_id                , c.c_id                , min(o.o_id) as min_order_id                , count(*) as no_of_orders         from suppliers s, clients c, orders o, items i         where s.s_id=c.id_s and c.c_id=o.id_c and o.o_id=i.id_o         group by s.s_id, c.c_id         )     )     where rnk=1 / 	0.000289164172872674
7549999	9200	how to produce multiple rows into 1 column value or sql statement with comma seperated in t-sql	select     'order by ' +       substring(       (       select           ',' + columnname +                 case isordered                    when 1 then 'asc'                  when 2 then 'desc'                end       from           mytable       where           isordered > 0        order by           seq_id       for xml path ('')       )       , 2, 7999) 	9.06585380716633e-05
7555270	27542	are you allowed to retrieve sequence inside a trigger	select seq_x_logsubno.nextval into groupid from dual; 	0.156941378786585
7581896	16328	sql - search a date-time period that doesn't exists in the table records	select * from your_table tb where    (  user_start_time <= tb.start_date_time and       user_end_time >= tb.start_date_time   ) or (      user_start_time <= tb.end_date_time and       user_end_time >= tb.end_date_time   ) or (      user_start_time >= tb.start_date_time and       user_end_time <= tb.end_date_time   ) 	0.000631288941072683
7585987	14880	restricting records to one side of the join in a self join query	select t1.id as termid1, t2.id as termid2     from         term t1          inner join term t2            on t1.uri = t2.uri          and t1.label <> t2.label          and t1.id < t2.id           where             t1.categoryid in (@categoryid1, @categoryid2)          and t2.categoryid in (@categoryid1, @categoryid2)               group by t1.id, t2.id     order by t1.id, t2.id 	0.0194707701800236
7589756	27789	how to find average without using group by statement in sql	select  e.emp_id ,     ( select    avg(salary)       from      #salary d       where     d.emp_id = e.emp_id ) from    #emp e 	0.0108951540643693
7596879	21444	selecting rows from table which have distinct values for a column	select message_reference.message_id, message_reference.receiver, messages.body from message_reference, messages where message_reference.message_id in (select  min(message_reference.message_id)                             from message_reference                             group by message_reference.receiver) and message_reference.message_id = messages.id and message_reference.sender = <sender> 	0
7599234	11442	select columns from another table and create a column	select a.width, a.height     from assigned_ads aa         inner join ads a             on aa.ad_id = a.id     where aa.id = 123  	0
7610227	22105	handling ambiguous column names	select ... from [table1] join [table2] on [table1].ambiguous_column = [table2].ambiguous_column and ... 	0.463847022543339
7611768	28414	sql query - select statement	select distinct y.cusid, y.name, isnull (y.s1, y.s0) as state from ( select x.cusid, x.name, ( select max ( state ) from address t where t.phyaddress = 1 and t.cusid = x.cusid ) as s1, ( select max ( state ) from address t where t.phyaddress = 0 and t.cusid = x.cusid ) as s0 from address as x ) as y 	0.734372125955491
7618173	21107	how could i write select statement to these two columns?	select a1, max(a2) as a2 from table group by a1 	0.15774889485248
7618899	14521	combining common values in sql	select t1.connectiona, t1.connectionb from yourtable t1 join yourtable t2 on t1.connectiona = t2.connectionb and t2.connectiona = t1.connectionb where t1.connectiona > t1.connectionb 	0.00527812732946501
7622306	17480	counting the size of a group in t-sql	select * from tablename where number in (    select number from tablename group by number having count(*)>3 ) 	0.00972693747746171
7640673	38348	how do you sum over a related period	select b.period, sum(a.value)   from table a      inner join period b on a.fiscalmonth between b.startmonth and b.endmonth      group by b.period 	0.00481309343908616
7653670	35061	how to use the sum query for specific rows	select members.member_id, members.teamname, sum(total_points) from members, members_leagues, member_results    where members.member_id = members_leagues.member_id      and members_leagues.league_id = '45'        and member_results.track_id = '1'           and member_results.member_id = members_leagues.member_id              and members_leagues.start_race >= member_results.track_id  group by members.memberid 	0.00495569932565289
7654756	18452	mysql query for selecting name based on condition	select name from users u where u.id not in (     select userid from usergroup ug     where ug.grpid = 1) 	0.0010814772400969
7661913	18517	modified preorder tree traversal: selecting nodes 1 level deep	select node.*, (count(parent.id) - 1) as depth from tree as node cross join tree as parent where (node.lft between parent.lft and parent.rgt) group by node.id having depth = {{enter your required depth here}} order by node.lft 	0.00981680407273395
7666556	10232	sql server loop in sproc to generate query	select col1   from table1 t        inner join        #temp v        on (t.col2 = v.col2) group by        col1 having count(*) = (select count(*) from #temp) 	0.498021540390721
7672422	38770	extracting values out of serialized php array in postgresql	select substring('... s:12:"searchtermid";s:4:"1008"; ....', 's:4:"([0-9]+)"'); 	0.00395790799246045
7679216	17989	sql - search method from 2 tables	select * from [table] t1 left join othertable t2 on t1.id=t2.id where   (     lower(t1.title) like '%$search%'      or lower(t1.contents) like '%$search%'     or lower(t2.meta_value) like '%$search%'   )   and t1.type = 'product' 	0.0483718887836795
7681984	19058	select max(date) rows before running where clause?	select url, max(date) as maxdate from history where uid = '19' group by url having  max( date ) <   (                         select max( h1.date )                         from history as h1                         where h1.url = 'canabalt.com'                              and h1.uid = '19'                         ) order by max( date ) desc 	0.259976102903678
7683424	13750	sqldeveloper: lowest paid employee for a specified manager. sample code given	select m.empno, min(e.sal) from emp e, emp m where e.super = m.empno group by m.empno having min(e.sal) > 1000 	0.00905920069385165
7686148	21253	sql view - exclude record before a date range	select authdate, productid, *  from productorders  where (not exists (select 1 from vwexcludeproductorders where productid = productorders.productid) and authdate < '2011-09-01') or authdate >= '2011-09-01' 	9.60742378709271e-05
7692004	30462	get uniqie views and views in one sql query	select distinct ip, `time` - `time` % 86400 as date, count(ip) as  views from `bvcms_pageviews` where 1=1 group by date 	0.011641287649174
7696248	27357	query giving duplicate result?	select distinct b.id,b.body from btin b inner join nwork n on (n.mem_id = b.mem_id)   where b.parentid = '0' and ('401' in (n.frd_id, b.mem_id)) order by b.date desc  limit 20 offset 0 select  b.id,b.body  from btin b where b.id in (select  b.id from btin b  inner join nwork n on (n.mem_id = b.mem_id)                   where b.parentid = '0' and ('401' in (n.frd_id, b.mem_id))) order by b.date desc  limit 20 offset 0 select  b.id,b.body from btin b inner join nwork n on (n.mem_id = b.mem_id)   where b.parentid = '0' and ('401' in (n.frd_id, b.mem_id)) group by b.id, b.body, b.date order by b.date desc  limit 20 offset 0 	0.371715817480341
7698274	33543	how to break down smalldatetime into year, month, day indexes?	select * from tablex where datepart(year,eventdate) = 1945 	0.000101196765488034
7709232	23996	mysql select with a count query on another table	select a.title as title, u.username as username, count(c.id) as total_comments from articles a    left join comments c on c.article_id = a.id    left join users u on a.user_id = u.id group by a.id 	0.00515398446045808
7723995	22863	selecting month and year from sql	select * from yourtable where col1 >= '2011-10-01' and col1 < '2011-11-01' 	0
7728130	12288	join last record based on timestamp	select a.username, a.entrydate, datediff(ss,a.entrydate, b.entrydate) secondsduration from yourtable a outer apply (select max(entrydate) entrydate              from yourtable              where username = a.username and entrydate < a.entrydate) b 	0
7731715	7773	how to work with derived tables	select c.companyname     from customers c     where exists(select null                      from orders o                          inner join [order details] od                              on o.orderid = od.orderid                                  and od.discount > .2                      where o.customerid = c.customerid) 	0.781633458577136
7736284	6626	show field dependent on whether other field contains data	select case when field1 <> ''              then field2          end as field2 from yourtable 	0
7758977	8835	how to add duplicate rows using sql sum function	select    min(card_id) as card_id,    tic_id,    game_id,    card_symbol,    card_symbol_no,    sum(qty) as qty from    yourtabel group by    tic_id,    game_id,    card_symbol,    card_symbol_no 	0.00662713026242095
7763894	36807	determine mysql mode from php	select @@sql_mode; 	0.0872506353851502
7774356	7537	mysql sum multiple columns	select team,        sum(score) as score,        sum(won)   as won,        sum(lost)  as lost from   (select idteamhome     as team,                sum(scorehome) as score,                sum(case                      when scorehome > scoreaway then 1                      else 0                    end)       as won,         sum(case               when scorehome < scoreaway then 1               else 0             end)       as lost         from   matches         where  status = 'played'         group  by idteamhome         union all         select idteamaway     as team,                sum(scoreaway) as score,                sum(case                      when scorehome < scoreaway then 1                      else 0                    end)       as won,         sum(case               when scorehome > scoreaway then 1               else 0             end)       as lost         from   matches         where  status = 'played'         group  by idteamaway) d group  by team 	0.0163301185255575
7774514	10676	how to i make a sql query check if the username is part of the email?	select username, substring(email, 1, locate('@', email)- 1) from usertable where lower(username) = lower(substring(email, 1, locate('@', email)- 1)); 	0.00659357226093035
7786570	28637	get another order after limit with mysql	select * from (     select *     from users     order by age desc     limit 10 ) as t1 order by name 	0.0080416577037721
7792626	23453	mysql query limitation	select memberid,group_concat(favorites_field) from allmembers a left join favorites f on (f.memberid=a.memberid) group by a.memberid order by f.date desc limit 10 	0.500458156425026
7796322	16245	comparing values in mysql table based on another tables rows	select users.name, app.* from applications app, users, postcodes where app.postcode like concat(postcodes.prefix,'%') and postcodes.user_id = users.id 	0
7806425	29019	related count within a query	select tbl1.buttonid,        tbl1.live,        tbl1.title,         tbl1.image,         count(tbl2.buttonid) as count   from buttons as tbl1  inner join (select buttonid from otherdb.buttonclicks b where b.type=0) tbl2     on tbl1.buttonid = tbl2.buttonid  group by tbl1.buttonid  order by tbl1.live desc, tbl1.buttonid asc 	0.046564965529399
7819200	14974	get column alias of column in query?	select count(*),count(*) as amount from projects 	0.00915144521232798
7828397	41019	select months and count months from date column	select month(datecolumn) as monthnumber, count(1) as occurances from schema.tablename group by month(datecolumn) 	0
7844716	28078	group and sum with dynamic column names	select year, type, count(type) from table_name group by year, type; 	0.0268281315357065
7852246	8649	what sql returns duplicates in first column where values in 2nd column differ?	select     id,     origin from     my_table t1 where     exists (select * from my_table t2 where t2.id = t1.id and t2.origin = 'rome') and     exists (select * from my_table t3 where t3.id = t1.id and t3.origin <> 'rome') 	0.00032021759152376
7865784	33419	treat column as different type for sorting	select name from tbl order by cast(stringcolumn as float) 	0.0161002200742859
7868687	27204	tsql - how to select some values from a table and some from sql variables?	select <columns>,@myvar as fromvar, '5' as fromconst from table 	0.000101774291384509
7872214	2060	sql: query to identify instances of an associated row in one table	select * from mytable a where a.name in (select t.name from mytable t group by t.name having count(distinct t.id) > 1) order by a.name, a.id 	0
7874678	3606	mysql null empty isset	select if(image_src is null or image_src = '', 0, 1) from table 	0.309816516322538
7890488	4190	how to perform a left join in sql server between two select statements?	select * from  (select [userid] from [user]) a left join (select [tailuser], [weight] from [edge] where [headuser] = 5043) b on a.userid = b.tailuser 	0.607225344222326
7895223	1877	generate columns from distinct values	select name, [rock climbing],[canoeing],[fencing],[archery] from  (select * from yourtable) p pivot (   sum(attendance)   for event in ( [rock climbing], [canoeing],[fencing],[archery] )  ) as pvt 	0.000157415647231133
7897722	27902	display values that are in table2 but not in table1	select column from table1 where column not in (select column from table2) 	8.44811848883392e-05
7911778	11293	how to query column matches for a row in a table?	select count(p.pc_id), p.pc_id from   member p group by p.pc_id 	0.000447716792722175
7918372	15703	can i combine local and remote dataset within sparql query?	select * where {   # the local part of the query   ?s ?p ?id   service <http:     # the remote part of the query     ?x ?y ?id   } } 	0.358768563080035
7920909	38082	return all rows where one field is the same, but there is at least one difference in the other fields	select t1.column1, t1.column2, t1.column3, t1.column4, t1.column5     from my_table t1         inner join my_table t2             on t1.column1 = t2.column1     where coalesce(t1.column2,'') <> coalesce(t2.column2,'')         or coalesce(t1.column4,'') <> coalesce(t2.column4,'') 	0
7921552	27737	tsql query to find equal row values along columns	select      case when count(col1) = count(*) and min(col1) = max(col1) then min(col1) end as col1,      case when count(col2) = count(*) and min(col2) = max(col2) then min(col2) end as col2,      ... from yourtable 	0
7931689	24551	oracle sql count() function?	select    nom_agence,    resp_agence,   sum(responsable) from    (     select        ag.nom_agence as nom_agence,        ag.responsable_agence resp_agence,        case           when l.duree > 3 then 1         else 0       end responsable     from        agences ag left outer join locations l on ag.id_agence = l.id_agence                                               and l.date_location                                               between to_date('01/01/2010','dd.mm.yyyy')                                               and to_date('31/12/2010','dd.mm.yyyy')    )  group by    nom_agence,   resp_agence 	0.797837688704962
7956835	37915	how can i filter data in an apex grid to show certain things for certain user groups?	select id, name, sector from employees where ((','||apex_util.get_groups_user_belongs_to(:app_user)||',' like '%,admin,%'       and sector = 'a') or (','||apex_util.get_groups_user_belongs_to(:app_user)||',' like '%,user,%'       and sector = 'h')) 	0
7969036	24166	query for selecting specific row in group	select company_id, node_id, [text] from t_tbl_data where row_id in (     select min(row_id)     from t_tbl_data     group by company_id, node_id ) 	0.00236454263260417
7991860	29347	mysql sum with if statement	select sum(badebet2_actual) from  (select if(badebet2 - bacredit2>0, badebet2 ,0) as badebet2_actual   from balansen) a; 	0.510930985058393
7995358	11982	get the value "18.18181818181818" using dividing in sql server?	select 2./11*100  	0.00586924070607633
7999126	40198	sql row grouping	select     date(ts) as date,     count(*) as entries from table group by date 	0.0459041272321489
8000325	12696	select statement depending on condition	select top 50 * from mytable where mykey > 1023 order by mykey 	0.0296004372745951
8011424	5046	mysql max between 2 columns of 2 joined tables	select max(certificate_number) as max from (     select certificate_number from contacts_cstm     union     select certificate_number from accounts_cstm ) as child 	0
8015418	34772	how to get table count even when query is limited?	select sql_calc_found_rows id,title,timestamp,votes from {$table} order by count desc limit 1, 20; select found_rows(); 	0.0150200123985005
8023886	38160	sql query for finding tables containing a column in my schema	select table_name   from user_tab_cols  where column_name = 'is_review_appeals' 	0.0558305655592935
8043693	37597	mysql regexp to match word list and any number of spaces	select * from t1 where descriptions regexp '((east|silicon|valley).*){3}()*'; 	0.000937010560927634
8046882	14465	count column data based on groupings	select a.`group number`,         sum(case b.featurea when 'yes' then 1 else 0 end) as feata,         sum(case b.featureb when 'yes' then 1 else 0 end) as featb,         sum(case b.featurec when 'yes' then 1 else 0 end) as featc  from tablea a join tableb b on a.username = b.username group by a.`group number` 	0.000862956318594934
8055120	12629	getting unique values in sql server	select t1.* from [mytable] t1 inner join (     select accid, min(date) date     from [mytable]     group by accid ) t2 on t1.accid = t2.accid and t1.date = t2.date 	0.0113966887980846
8070927	21937	mysql many-to-many select	select m5.name     from mark5 m5         inner join mark4 m4             on m5.uid = m4.uid         inner join mark3 m3             on m4.phoneid = m3.phoneid     where m3.name in ('htc', 'samsung')     group by m5.name     having count(distinct m3.name) = 2; 	0.31894418128565
8073317	12985	summing in mysql	select sum(case when t1.type_id = 4 then 0 else t1.value end) as s123,         sum(case when t1.type_id = 4 then t1.value else 0 end)  as s4 from test as t1 where t1.type_id in (1,2,3, 4) 	0.208099567666666
8106031	13988	mysql query foreign key referencing primary key	select u.*, up.name from units u left join units up on u.parent_id = up.id 	0.00548922308627894
8106547	13419	how to search on mysql using joins?	select p.* from posts p   inner join posts_tags pt1 on p.id = pt1.post_id    inner join tags t1 on pt1.tag_id = t1.id   inner join posts_tags pt2 on p.id = pt2.post_id   inner join tags t2 on pt2.tag_id = t2.id where (t1.name, t2.name) = ('water', 'blue')             and not exists       ( select *         from posts_tags pt           inner join tags t on pt.tag_id = t.id         where p.id = pt.post_id            and t.name in ('black', 'white', 'red')            ) 	0.600121921574466
8108897	29079	sql select command	select e.empno, e.empname, s.empname from eployee as e left join eployee as s on e.supervisors = s.empno 	0.555094135944
8110340	11777	sql query for counting the number of categories	select prodtype, count(1) from prodinfo group by prodtype 	0.000871694730707025
8138199	15328	set value on sqlbulkcopy	select name, age, 'all' as cat from tablename 	0.0247290051131467
8142163	35118	unique records based on same ids with different type	select t1.id,t1.email,t2.role  from   table t1, table t2 where  t1.id=t2.id    and  t2.id = t2.assigned_id 	0
8151601	28932	combine 2 sql queries	select num_rata, sum(val_imp)*0.01 imp_amount, sum(val_ban)*0.01 ban_amount from (select num_rata, val_imp, 0 val_ban       from table1       where col1 <> 0 and num_contract = 88       union all       select num_rata, 0 val_imp, val_ban       from table2       where num_contract = 2988) v group by num_rata; 	0.0530676972165358
8152549	15927	generate html from sql table	select 'employee' as '@class',        a1.employeeid as '@employeeid',        max(a1.employeename) as '@employeename',        (select 'action' as '@class',                left(a2.actionstart, 5) as '@start',                left(a2.actionend, 5) as '@end',                a2.type as '@type'         from #actions as a2         where a1.employeeid = a2.employeeid         for xml path('div'), type) from #actions as a1 group by a1.employeeid for xml path('div') 	0.00528927332183618
8158998	12890	selecting distinct values in a mysql table	select l.userid, u.username, l.lid, l.rank, l.win, l.loss, l.streak, l.score     from (select userid, max(score) as maxscore               from league                group by userid) q         inner join league l             on q.userid = l.userid                 and q.maxscore = l.score         inner join users u             on l.userid = u.userid 	0.000847449990954807
8164585	29567	how to have leading zeroes	select right('0000' + cast(id as varchar(4)), 4) from table1 	0.0719354953972737
8169792	30121	how to find values in all caps in sql server?	select * from t   where fld = upper(fld) collate sql_latin1_general_cp1_cs_as 	0.000841697253336164
8170732	6101	using t-sql 'two digit year cutoff' in script	select value from sys.configurations  where name = 'two digit year cutoff' 	0.0175457847905041
8181100	22290	fetching product categories in one row with product info	select p.product_id, p.product_title,        group_concat(c.category_title) from products p   inner join products_categories pc on p.product_id = pc.product_id   inner join categories c on pc.category_id = c.category_id group by p.product_id 	4.72035174733978e-05
8183634	25038	check for appearance of multiple strings in mysql	select distinct class from table; 	0.00905856054207193
8184626	1319	mysql sum() subquery with min()	select  etp_product.product_id,   etp_product.price,   (select min(price) as field_2 from etp_product_option_value pov where pov.product_id = etp_product.product_id) as option_price,  etp_product.price + (select min(price) as field_3 from etp_product_option_value pov where pov.product_id = etp_product.product_id) as total from   etp_product group by   etp_product.product_id,   etp_product.price 	0.519510090503447
8189519	8171	combine results in one row from multiple rows based on criteria from same table	select acpj.id    , case         when acpj.grade is null or acpj.grade = '' then ac.grade         else acpj.grade      end as finalgrade from sag as acpj inner join sag as ac on acpj.id = ac.id where acpj.resultgroup = 'acpj'    and ac.resultgroup = 'ac' 	0
8194953	37563	mysql join 3 tables - multiple join	select tf.html_embed_before    , sf.path    , tf.html_embed_after from type_files as tf inner join script_files as sf on tf.type = sf.type inner join script_match as sm on sf.id = sm.file_id where sm.ap_id in (    select a.head    from article as a    where a.id = @yourid    union all    select h.head    from header as h    where h.id = @yourid    union all    select f.head    from footer as f    where f.id = @yourid ) 	0.268729702053828
8203209	1383	paging results from a table having a varchar as pk	select r.name, r.status. r.description from (     select t.name, t.status. t.description, rownum rownumber     from     (         select name, status, description         from yourtable         order by name asc     ) as t     where rownum < (pagenumber * pagesize) + 1 ) as r where rownumber >= ((pagenumber - 1) * pagesize) + 1 	0.085319350184509
8220107	19031	default getdate() always stores am for time in sql server	select convert(varchar(20), getdate(), 100) 	0.54435994802993
8220398	21733	unable to select rows from the last 7 days	select * from follows  where cast(date as date) between date_sub(curdate(), interval 7 day) and curdate() group by `followed` 	0
8236129	4702	distinct on column only for non null values	select distinct on (parent_id) *     from messages     where parent_id is not null   union     select * from messages where parent_id is null 	0.000302065081523508
8239698	27638	make a normal query from a stored procedure	select personid from t_person where      ccode = (         case when @ccode = 'all'  then ccode         else @ccode end         )     and     empcode = (         case when @empcode = 'all'  then empcode         else @empcode         end         ) 	0.504101233291964
8258632	30465	how to update tables with nvarchar(max) columns with minimal locks	select * from thistable (nolock) 	0.0723904948017181
8278375	24001	mysql: how to get top 10 and remaining?	select * from name order by id asc limit 10, 999999 	0.00015617267709902
8284626	40364	mysql - query to return csv in a field?	select f.foo_id, group_concat(t.name) as tags from foo f, tag t, foo_tag as ft where f.foo_id = ft.foo_id and ft.tag_id = t.tag_id group by f.foo_id 	0.0164967948690722
8293462	10667	reading data from multiple tables (vb)	select    o.col1, c.col2, ... from    orders o    join    customers c on o.customerid = c.customer where     ... 	0.0319237851760117
8297488	24185	mysql case statements using dates	select   id,   case     when date_activated > '2011-11-23 18:30:00' then 'after'     when date_activated > '2010-01-20 00:00:00' then 'before'     else 'not yet'   end as date_note from table1; 	0.690390749459813
8300610	31609	count many items in one query	select      `p`.`name` as `name`,     `i`.`itemtype` as `item`,     sum(`i`.`count`) as `count` from     `player_items` as `i` left join      `players` as `p`     on         (`p`.`id` = `i`.`player_id`) where      `i`.`itemtype` in (2148, 2152, 2160)  group by     `i`.`player_id`,     `i`.`itemtype` 	0.00393562842677265
8309923	8344	mysql multiple join and exclude	select x  from tablea     left join tableb on tablea.x = tableb.x     left join tablec on tableb.y = tablec.y and tablec.z != 'excluded' where     tableb.x is null     or tablec.y is not null 	0.106048679885032
8311004	20456	how to get last row value in mysql database	select s.*, @rownum:=@rownum+1 as rank from your_table s, (select @rownum:=0) r order by rank desc limit 1; 	0
8316974	389	sqlite3 select field by numeric range, expanded, pt2	select *  from   en  where  ( type = 's'            or type = 'w' )         and ( value1 between 15 and 16.6               and value2 between 30.0 and 40.0 ) 	0.00803924919825269
8321009	9404	select n posts per category in a single query	select i.*  from wp_term_relationships rel inner join (    select p.*, rel2.*    from wp_posts p   inner join wp_term_relationships rel2           on (rel2.object_id = p.id)    where rel2.term_taxonomy_id = rel.term_taxonomy_id   order by p.post_date desc    limit 2 offset 0 ) i on (i.object_id = rel.object_id) where rel.term_taxonomy_id in ('3','4') order by i.term_taxonomy_id asc, i.post_date desc 	0
8331951	10309	calculate diffference between 2 dates in sql, excluding weekend days	select sysdate - creation_dttm - 2 * (to_char(sysdate, 'ww') - to_char(creation_dttm, 'ww')) from the_table 	0
8334108	32324	how do i select a maximum date from sql server 2005 xml column?	select  testxml.value('(/test/@name)[1]', 'varchar(100)') name,         testxml.value('(/test/@status)[1]', 'varchar(100)') statuscol,         bar.ctrl.value('(control/@requestdate)[1]', 'varchar(100)') requestdate into #dates from testxml cross apply testxml.nodes('/test/bar') bar(ctrl) where testxml.value('(/test/@status)[1]', 'varchar(100)') = 'completed' select name, statuscol, max(requestdate) from #dates group by statuscol, name 	0.000382803474258914
8347308	15998	group by two column but show more data from the table - payout issue	select a, b, min(y), max(z) from table group by a, b 	0.000255928926257739
8350149	6638	list record from table by selects max value	select branch_code,acc_number,acc_balance from (         select distinct acc_number,branch_code,acc_balance,          max(acc_balance) over(partition by branch_code order by 1) as max          from account )     where acc_balance=max 	0
8351327	35657	php mysql most liked query for last 100 records	select * from (select * from likes order by date desc limit 100) xx group by url order by count(*) limit 6 	0.000135424604194059
8363914	25299	how do i limit the results of an sql query?	select id from table limit 5 	0.120543520678992
8369240	19624	getting rows that contain key1 and don't contain key2	select i.* from items as i inner join item_keywords as ik on i.item_id = ik.item_id where keyword_id = 1    and ik.item_id not in    (       select item_id       from item_keywords       where keyword_id = 3    ) 	0.00085266686242848
8370512	38298	gae: best way to add (math) all values of an integer property from multiple instances	select __key__ from grade where points > 0 	0
8377659	41319	how to change this mysql query to select from one table instead of two?	select      user_id,                 zip,                  latitude,                  longitude,                  (acos(sin($lat) * sin(radians(latitude)) + cos($lat) * cos(radians(latitude)) * cos(radians(longitude) - $lon)) * $radius) as searchradius      from users     where (latitude > $min_lat and latitude < $max_lat)      and (longitude > $min_lon and longitude < $max_lon)     and (acos(sin($lat) * sin(radians(latitude)) + cos($lat) * cos(radians(latitude)) * cos(radians(longitude) - $lon)) * $radius) < $rad      order by searchradius 	0.000270953967436333
8386587	16605	sqlite grouping	select a, count(distinct c), count(*)  from xyz group by a; 	0.284116106143882
8395312	20406	storing and retrieving historical data of user's learning progress - php/mysql	select * from 'user_topics' where 'datetime' between '2008-12-23' and '2008-12-25'; 	0.00277073643119437
8400517	32997	count for groups and sub-groups	select    month([date]) [month],    year([date]) [year],    count(*) [total],    count(case when status in ('gone', 'cancelled') then 1 end) [lost],    count(case when status= 'won' then 1 end) [won] from    mytable group by    month([date]),    year([date]) 	0.0656828131452688
8400657	24276	mysql include count does not return rows with count zero	select count(*) as cnt, c.c_id, c.cdesc  from c  left join e on c.c_id = e.c_id  group by c.c_id 	0.0490215597988512
8418286	24661	sql group by month	select date_year, date_month_number, date_month_name, service, sum(hours), sum(days), projectname, sum(cost) from dbo.resources_group_projectname where (service like '%housing%') group by projectname, date_year, date_month_number, date_month_name, service order by date_year, date_month_number 	0.0245123242721443
8425048	34060	read a text/csv file from an sql statement	select emp_record from emp_data where emp_no in ( ... paste contents of file here. ) 	0.407727430242755
8431854	8616	sql group sort by date	select t1.* from table t1 left join table t2  on t1.type = t2.type and t1.created < t2.created where t2.id is null 	0.0615672009759564
8434506	6246	sql queries executed at a give time window on oracle server	select a.sql_id,dbms_lob.substr(b.sql_text,4000,1) from dba_hist_active_sess_history a, dba_hist_sqltext b where sample_time between to_date('20110711:15:20','yyyymmdd:hh24:mi') and to_date('20110711:15:21','yyyymmdd:hh24:mi') and b.sql_id=a.sql_id union all select a.sql_id ,dbms_lob.substr(b.sql_text,4000,1)from v$active_session_history a ,v$sqlarea b where sample_time between to_date('20110711:15:20','yyyymmdd:hh24:mi') and to_date('20110711:15:21','yyyymmdd:hh24:mi') and b.sql_id=a.sql_id 	0.711496194321724
8434582	32396	dog year birthdate query	select id from dogs where datediff (curdate(), birthday) %52 = 0; 	0.0417880933327255
8446032	37112	oracle grouping/changing rows to columns	select key,     max(decode(id_col,1,id_col)) as id_1,max(decode(id_col,1,val)) as val_1,     max(decode(id_col,2,id_col)) as id_2,max(decode(id_col,2,val)) as val_2,     max(decode(id_col,3,id_col)) as id_3,max(decode(id_col,3,val)) as val_3 from (         select key, row_number() over (partition by key order by id) as id_col,id,val         from your_table     ) group by key 	0.00602665591414924
8446710	35056	how to count values in a single row?	select id,        (select count(*)         from   (values (x1),                        (x2),                        (x3),                        (xn)) t(x)         where  x = 'x') as num from   yourtable 	0.000270094022540759
8447793	11799	oracle - ora-01422: exact fetch returns more than requested number of rows	select sum(payment_amount)     into total_payment_amount     from payment     where order_no = :new.order_no       and payment_status = 'successful'; 	7.65322754667723e-05
8449897	22069	display duplicate records in mysql table	select *     from table1 t  inner join           (             select street_number, street_name, unit_number, zip_code               from table1 t1              group by street_number, street_name, unit_number, zip_code             having count(distinct mls_id) > 1           ) t2 on t.street_number = t2.street_number and t.street_name = t2.street_name and         t.unit_number = t2.unit_number and t.zip_code = t2.zip_code 	6.760334900518e-05
8470245	24411	how to group by column, order by a different column, and limit each group to one row?	select ns.name, max(ns.score) as score from namescore as ns group by ns.name order by ns.name asc 	0
8473706	6497	retrieve all tables selectable by a user (in oracle)	select table_name from table_privileges where grantee='user' and select_priv='y' union select table_name from  user_tables 	0.00153972531415431
8480795	27678	mysql: log summary query	select        a.id,       a.active,       a.static,       a.position,       a.file,       a.title,       a.url,       coalesce( preagg.cntviews, 0 ) views,       coalesce( preagg.cntclicks, 0 ) clicks    from       ads as a        left join           ( select lv.ad_id,                   sum( if( lv.type = 'view', 1, 0 )) as cntviews,                   sum( if( lv.type = 'click', 1, 0 )) as cntclicks               from                  ad_log lv               where                      lv.type in ( 'view', 'click' )                  and lv.created between '2011-01-01 00:00:00'                                     and '2011-12-31 23:59:59'                group by                   lv.ad_id ) preagg         on a.id = preagg.ad_id 	0.509121795684815
8482491	35365	searching for specific entity name in sql xml table columns	select @x.query('( 	0.00293201794983004
8491695	16251	query for joining all info from three tables	select users.userid,        items.description,        usersitems.value from        users cross join        items left join        usersitems on        users.userid = usersitems.userid and        items.itemid = usersitems.itemid 	0.000177157590230143
8491770	33349	php mysql select id from one table and information from another table	select i.id, i.name, i.phone from `queuelist` as q left join `info` as i on (     q.clientid = i.id ); 	0
8497928	29017	mysql - find duplicates cross relational table	select      b.`website_id`, a.sku,      group_concat(distinct a.`product_id`) as sku_products  from `products` as a       left join `website_products` as b           on ( a.`product_id` = b.`product_id` )  group by b.`website_id`, a.`sku`  having count(distinct a.`product_id` ) > 1 order by b.`website_id` 	0.067768801817296
8510417	40402	mysql query to return specific row value depending on	select     t1.*,    (case when t2.columnb is not null then 'yes' else 'no' end) as columnx from    table1 t1    left outer join    table2 t2      on  t1.columnb = t2.columnb 	0
8510454	221	combining the data in two columns into one for sorting	select mls_sort from (     select mls_agent_id as mls_sort        from mlsdata      where mls_agent_id = $agent_narid     union     select mls_office_id as mls_sort        from mlsdata      where mls_office_id = $office_narid ) order by mls_sort 	0
8512912	27007	mysql: translate id's to values	select car_make, car_engine, car_model, car_radio,        buyer, seller, car_title, sale_price from cars_sold join car_make_lookup using (car_make_id) join car_engine_lookup using (car_engine_id) join car_title_lookup using (car_title_id) join car_model_lookup using (car_model_id) join car_radio_lookup using (car_radio_id) join buyer_lookup using (buyer_id) join seller_lookup using (seller_id) join car_title_lookup using (car_title_id) 	0.0110337942810845
8513282	37600	select the category with the most entries in the database	select categoryno, count(entryno) as numentries from entries group by categoryno order by numentries desc limit 1 	0
8514317	35457	how to group by field then order by different field then limit	select        t2.*,        m2.*    from       ( select t.thread_customer_id,                max( m.message_time ) as latestpost            from               _threads t                  join _messages m                     on t.thread_id = m.message_thread_id            where               t.thread_servicer_id = 'jg5s2b6trs'            group by                t.thread_customer_id ) premax       join _messages m2          on premax.latestpost = m2.message_time          join _threads t2             on m2.message_thread_id = t2.thread_id            and t2.thread_customer_id = premax.thread_customer_id            and t2.thread_servicer_id = 'jg5s2b6trs'    order by        m2.message_time desc 	0.000229938735716908
8515039	2642	efficient way to check for the existence of a single mysql record?	select 1 from dual where exists (     select *     from  employee_department ed     where ed.employee_id = '%d'         and   ed.department_id = '%d' ) 	0.000217688430211179
8524703	38764	every derived table must have its own alias	select `snap`.`id`, `user`.`username`, `vote`.`type`  from (`snap`) join `user` as u on `u`.`id` = `snap`.`user`  left join (select * from vote where user = "18") as vote on `snap`.`id` = `vote`.`snap`  join (select ceil(max(id)*rand()) as id from snap) as x on `snap`.`id` = `x`.`id`  where `snap`.`active` = 0 limit 1 	0.00269542106997422
8528491	31638	mysql not equal to "in" query	select * from table where id not in (10, 88, 99) 	0.498867056180646
8528666	6640	highscore table - how to highest score per user?	select name, max(score) from highscores group by name order by max(score) desc limit 10 	0
8532283	12934	mysql numbers in varchar columns query issue	select max(cast(op_calcul as signed)) from nom_prod... 	0.167282480899709
8533910	8889	pl/sql function to view maximum salary	select salarydata('finance','max') as max_sal from dual; 	0.031104332619485
8544438	10400	mysql now() -1 day	select * from foo where my_date_field >= now() - interval 1 day 	0.00319110802767907
8554450	212	export mysql table using order by	select * from `wp_events` order by `wp_events`.`event_start_date` asc mysqlmysqldump into outfile 'file_name'   	0.113896803486508
8562195	39361	how to create new date from 3 columns in sql	select data, dateadd(month, 1, data) from table 	0.00013849277041963
8563582	10560	how to filter table column id into corresponding name directly with a sql query	select name =     case columnid       when '11' then first        when '12' then second    end,    starttime, endtime from yourtable 	6.428020398612e-05
8566106	15841	mysql outer join, doesn't return non-matching rows	select * from external_review_sources a left join      listing_external_review_source_rel b on a.ersid=b.ersid and bid=866696; 	0.436321019395182
8567192	5080	pull rows from database in certain order (not using order by)	select *     from tblmerchants     where merchantid in (18, 36, 90)     order by case when merchantid=36 then 1                   when merchantid=90 then 2                   when merchantid=18 then 3                   else 4              end 	0.000113863069656206
8580139	314	can i alias a column with an as in the select part of a mysql query?	select distinct(users.user_id),     (select resi.curr_state            from ci_residents              as resi_1 where resi_1.user_id = users.user_id) as current_state from     ci_users as users, ci_residents as resi ..... where stuff having current_state = '".$php_variable_ill_use."' 	0.0689173686176545
8589312	5490	array in oracle block	select regexp_substr(var_presentaddress1, '[^,]+', 1, rownum)    bulk collect into emps   from dual   connect by level <= length (regexp_replace (var_presentaddress1, '[^,]+'))  + 1); 	0.273689288875372
8601162	35623	order by last 3 months first, then alphabeticaly	select * from products order by datecolumn > curdate() - interval 3 month desc, productname; 	0
8606580	32833	query to find all the providers that offer all the services	select ps.providerid     from provider_service ps         inner join @idservices i             on ps.serviceid = i.serviceid     group by ps.providerid     having count(distinct ps.serviceid) = (select count(*) from @idservices) 	0.00101189594087008
8607743	29839	find all log events of type a that occur between types b and c	select * from eventlog e join (     select          process_id,          min(case event when 'eventb' then time end) start_time,         max(case event when 'eventc' then time end) end_time     from eventlog     group by process_id ) t     on e.time between t.start_time and t.end_time where     e.event = 'eventa' 	0
8624492	6831	mysql - two table query, with sum	select c.id, c.email, count(o.customer) as numorders   from customers c    inner join orders o on (o.customer=c.email)    where o.siteid= 'calico'   group by c.id, c.email 	0.0378706936285158
8629925	29341	mysql subquery(or union?)	select t1.testid, t1.username, t1.topic, t1.information, t1.totaltime,     (select count(questionid) from table2 t2 where t2.testid = t1.testid) as 'questioncount' from table t1 	0.464778361745971
8638507	9468	mysql query logic for fetching posts by dates	select created as date_a from posts order by created desc limit 99, 1 select   (last_day(created) + interval 1 day - interval 1 month) as date_b from posts order by created desc limit 99, 1 	0.0285249078366741
8640344	19384	mysql count union results that don't overlap	select count(distinct id) from (select id from jokes where flags < 5 and (title like ? or joke like ?)        union       select id from jokes where flags < 5 and (title like ? or joke like ?)        union       select id from jokes where flags < 5 and (title like ? or joke like ?)) t 	0.0229850079695213
8642644	34286	mysql's different quote marks	select * from `test` where `x` = '1' 	0.715396991675491
8652194	16280	how to tune the following oracle10g query?	select distinct t1.destination,                       t1.digitsmin,                       t1.digitsmax,                       t2.destination,                       t2.digitsmin,                       t2.digitsmax,                       's'         from my_codes t1         join my_codes t2           on t1.rownumber <> t2.rownumber          and t1.typ = t2.typ        where t1.mycarr= 73          and t1.typ = 's'          and t1.digitsmax >= t2.digitsmin          and t1.digitsmin <= t2.digitsmax; 	0.758332148573618
8652284	8846	fastest way to check if set exists in database set	select exists(select 1 from table1 url = 'foo' or url = 'bar' or ... ) 	0.0213584585479014
8655696	16495	sql server query?	select id_local,        count(*) as total,        count(case when id_status = 0 then 1 end) as status0,        count(case when id_status = 1 then 1 end) as status1,        count(case when id_status = 2 then 1 end) as status2 from yourtable group by id_local 	0.698580681859737
8656394	35514	will the following two queries give the same output consistently?	select deptno from   dept where  exists ( select *                 from   emp x                   join emp y                     on y.job=x.job                 where  x.deptno = 20                   and  y.deptno = dept.deptno                )    and  deptno <> 20; 	0.00715734474803018
8657075	12883	query to find distance between a point column and a point in postgis	select the_geom from mytable where st_dwithin(the_geom,st_geomfromewkt("srid=4326;point(lon lat)"), 0.0008); 	0.00464366624874541
8668866	27516	trying to get data with one fixed where statement and another one which is optional	select * from strings  left join translations on strings.hash = translations.string and language = 'fr' where strings.project = 'kg6k34j6' 	0.000275902495830305
8684387	20090	how to combine several select statements into one table	select      sum(case when results.choice = p.choice1 then 1 else 0 end) as choice1count,     sum(case when results.choice = p.choice2 then 1 else 0 end) as choice2count,     sum(case when results.choice = p.choice3 then 1 else 0 end) as choice3count,     sum(case when results.choice = p.choice4 then 1 else 0 end) as choice4count,     sum(case when results.choice = p.choice5 then 1 else 0 end) as choice5count from      students_answers_polls as results     inner join polls p on         results.poll_id = p.poll_id         and results.choice in (p.choice1, p.choice2, p.choice3, p.choice4, p.choice5) where      results.poll_id = @poll_id      and course_page = @course_id 	0.000293451775747691
8690450	29306	making a table display records from multiple tables and as well as adding new records at the same time	select name + ', ' + age + ', ' + gender as description ,          datecreated     from table1   union   select carmake + ', ' + model + ', ' + year as description ,          datecreated     from table2 order by datecreated 	0
8697710	12527	how to use a condition with "count" in mysql?	select count(*)  from `nagios`.`nagios_hostchecks`  where `nagios_hostchecks`.`start_time` like '%2012-01-02%'      and  `nagios_hostchecks`.`host_object_id`=60     and `state` = 0; 	0.360813866863809
8713266	31876	how do i sort by a specific order	select *  from users  order by case id when 2 then 1                  when 3 then 2                  when 1 then 3          end 	0.0192126459963513
8713476	13695	join table on itself - performance	select *  from money m inner join (     select memberid, max(id) as maxid     from money     group by memberid ) mmax on mmax.maxid = m.id and mmax.memberid = m.memberid 	0.716984909531716
8715779	24366	using php to compare 2 tables and create a list on another table	select * from logs natural join employees where entry > schedule 	0
8717500	10652	postgresql view column naming	select      co_url_name,      score_combined,     (select trunc(("productandservices" + "futurepurchase" + shipping + "customerservice" + returns + "lifetimerating")/6, 2)) as resellerrating 	0.325096653720386
8732908	38680	mysql column in	select *     from yourtable     where find_in_set('2', numbers) <> 0 	0.113288426403992
8749624	8791	sql query to get results from various tables	select      userid,     firstname,     lastname,     email,     phone,     stuff((select ',' + n.unitnumber from dbo.units n where n.userid = u.userid for xml path('')), 1, 1, ''),     stuff((select ',' + p.parkingspot from dbo.parking p where p.userid = u.userid for xml     path('')), 1, 1, '') from users u 	0.000967707289020882
8762886	21322	sql group by age range	select sum(case when age_c < 18 then 1 else 0 end) as [under 18],         sum(case when age_c between 18 and 24 then 1 else 0 end) as [18-24],         sum(case when age_c between 25 and 34 then 1 else 0 end) as [25-34]  from contacts 	0.00878763264703417
8767323	18455	how best to get someone's 'rank' from a scores table with php and mysql without looping	select s1.initials, (   select count(*)   from scores as s2   where s2.score > s1.score )+1 as rank from scores as s1 	0.000445291359795213
8768716	9568	how to correctly query database for results that contain lists	select o.id, l.quantity, p.name, p.price, a.address, l.quantity * p.price subtotal, (     select sum(l1.quantity * p1.price)     from line_items l1     inner join products p1 on l1.product_id = p1.id     where l1.order_id = o.id ) ordertotal from orders o inner join line_items l on o.id = l.order_id inner join products p on l.product_id = p.id inner join addresses a on o.address_id = a.id order by o.id, l.id 	0.547029986899116
8771980	4544	how to tally wins and losses using sum and case?	select  sum(case when vote = 1 then 1 else 0 end) as wins,     sum(case when vote = 0 then 1 else 0 end) as losses from     votes where    bikeid = 101 	0.570573180457384
8776799	23960	mysql date between for todaydate	select * from table  where date_format(created_date,'%y-%m-%d') = date_format(curdate(),'%y-%m-%d') 	0.0307858991047255
8776874	31864	reducing table so as to get island	select a.* from tablex as a where exists       ( select *         from tablex as b         where b.x = a.x           and ( b.z = a.z + 1              or b.z = a.z - 1               )       ) 	0.159546715804352
8777140	12492	get random row from table (but only if the row contains a specific value)	select * from table where color = 'red' order by rand() limit 1 	0
8800509	2002	sql -- merge only some columns from different tables	select id_post, id_user,  title,  content, null as message , published, nbr_comments, timestamp from posts_article union select id_post, id_user, null as title, null as content,  message, null as published, nbr_comments, timestamp from posts_text 	0
8804722	30790	sql server 2008+ : best method for detecting if two polygons overlap?	select ct.id as ctid, ct.[geom] as censustractgeom from censustracts ct where ct.[geom].stintersection(@radiusgeom).stastext() <> 'geometrycollection empty' 	0.65118901283506
8810696	7734	sql search function to order by appearance in columns	select     * from     table where     keywords like @searchstring     or answer like @searchstring     or question like @searchstring order by     case when keywords like @searchstring then 0          when answer like @searchstring then 1          else 2     end 	0.183940036984514
8812724	21971	counter number of items within each time period in mysql	select date_format(from_unixtime(regdate), '%y-%m') as month,         count(*) as registrations  from users  group by month 	0
8823487	7391	sql: filtering rows	select        id, name from    (     select              row_number() over (partition by p.name, p.operation order by p.id desc) rn ,              id,               p.name,             p.operation,              operationcounts.insertcount,             operationcounts.deletecount     from         person p     inner join (         select            sum(case when operation = 'insert' then 1 else 0 end) insertcount,           sum(case when operation = 'delete' then 1 else 0 end) deletecount,           name          from             person          group by            name ) operationcounts     on p.name = operationcounts.name     where        operationcounts.insertcount <> operationcounts.deletecount) data where       (rn <=  (insertcount -  deletecount)       and operation = 'insert')       or      (rn <=  (deletecount -  insertcount)       and operation = 'delete') 	0.059187640240753
8835057	14161	mysql query booking system - remove entry if room is already booked	select * from room where room.view = :view and room.type = :type and (select count(*) from reservation r where r.room_id = room.id and  (r.checkout > :checkin and r.checkin  < :checkout) or (r.checkin  < :checkin and r.checkout > :checkin))  = 0 	0.0160074755811391
8837417	24441	unable to get mysql to recognise query using in statement	select * from events where discipline in ('sj','other') 	0.473558257754203
8843332	18668	mysql min and max date with group by and substring	select somedate,somemessage from sometable inner join ( select min(somedate) as somedate from sometable) earliest on earliestdate.somedate = sometable.somedate 	0.0612140041044906
8844153	8577	european format time - convert string to datetime in sql	select convert(datetime, '21-04-2010 11:06', 105) 	0.0144548089437914
8850290	35996	distinct union on select. errors on ntext data type	select products.productid,        name,        introduction,        description,        active,        material,        colour,        dimensions,        photo,        price,        displayorder,        friendlyurl,        productreference,        categories_products_lookup.categoryid from   products        inner join categories_products_lookup          on products.productid = categories_products_lookup.productid where  active = 1        and ( products.description like '%' + @keyword + '%'               or products.name like '%' + @keyword + '%' ) order  by case             when products.name like '%' + @keyword + '%' then 0             else 1           end 	0.442947386386884
8856896	5503	need to select rows from the table with a version column which match the latest version	select * from (    select id,            value1,            value2,            version,           max(version) over (partition by id) as max_version     from t     where id in (1, 2, 3, ... 10) ) t2 where version = max_version 	0
8866110	3896	query doesn't show all the results that i need	select * from people where name = 'tim'  union  select 'null', building, null, null from   people where name != 'tim'; 	0.0163330333843029
8885470	8714	sum the count of days in many intervals	select t1.cli ,        sum(t1.countable  *             datediff(day, t1.[date], coalesce(t2.[date],getdate())) ) daycount from datadiff t1 left join datadiff t2 on t1.cli = t2.cli and t1.id+1 = t2.id group by t1.cli 	0
8900848	32866	summing sales across different currencies in sql	select  title,          partner_share_currency,         sum(us_earnings_usd) as usd,         sum(cad_earnings_cad) as cad,         sum(us_earnings_usd) + sum(cad_earnings_cad*cad) +         sum(uk_earnings_gbp*gbp) + sum(swedish_earnings_skk*sek) total_earnings_in_usd from raw_financials rf left join ( select  date,                      min(case when  currency = 'cad' then conversion_to_usd end) cad,                     min(case when  currency = 'gbp' then conversion_to_usd end) gbp,                     min(case when  currency = 'sek' then conversion_to_usd end) sek             from exchange_rates              where currency in ('cad','gbp','sek')             group by date) er on rf.date = er.date where title like '%gamers%' and rf.date= '2012-12-01' group by title 	0.00355327155512792
8906600	41250	how to fetch all the rows based on conditions greater than or lesser then?	select * from emp_info where salary between 10000 and 25000 	0
8916799	1332	want to select the  minimums of the result	select name, min(id) as 'id' from people group by name 	0.00502415371880319
8928068	37518	how to display 0 if the count of distinct values is null?	select trim(vendor) || ' ' || trim(location) || ' ' || trim(type1) as vendor_location,        count(distinct case                when (rating = 'needs improvement' or rating = 'unacceptable') and "year" = '2011' and quarter = 'q3' then                 control_objective                else                 null              end) as "cont obj"   from some_table  group by trim(vendor) || ' ' || trim(location) || ' ' || trim(type1)  order by trim(vendor) || ' ' || trim(location) || ' ' || trim(type1); 	6.06967957490525e-05
8931528	14504	multiple count on same column with where like - mysql	select system_user,      sum(case when details ='viewed' then 1 else 0 end) viewed_count     sum(case when details like 'viewed web%' then 1 else 0 end) viewed web_count     sum(case when details = 'thumbview' then 1 else 0 end) thumbview_count     sum(case when details like 'exported%' then 1 else 0 end) exported_count from asset_log  where      details = 'viewed' or     details like 'viewed web%' or     details = 'thumbview' or     details like 'exported%'   group by        system_user 	0.0295938362738133
8939046	11921	sql server: two cursors iterate	select distinct ... from tablename 	0.469797746747278
8943469	31210	how to select info from row above?	select [no_]   ,[name]   ,[account_type]   ,[subgroup]   ,lag([no_]) over(partition by [subgroup] order by [no_]) as [prevvalue] from table 	0.000186525331047553
8944375	2508	postgresql: how do i export a function definition to sql	select  proname, prosrc from    pg_catalog.pg_namespace n join    pg_catalog.pg_proc p on      pronamespace = n.oid where   nspname = 'public'; 	0.740169855120133
8960467	32068	mysql: how to delete rows from the set?	select txt.line_id,           txt.text as o,           coalesce (ru.text,'untranslated') as t  from    text as txt left join    text as ru  on txt.line_id=ru.line_id and ru.lang='ru' where txt.lang='en' 	0.00038731658562921
8978298	22663	combining 2 select expression with limit in both	select * from      (       select * from          (select * from questions where level=1 limit 5)        union          select * from          (select * from questions where level=2 limit 5)     ) 	0.23424990933892
8985434	8296	using mysql outfile with non-simple data	select *   into outfile 'output.csv'     fields terminated by '\t' enclosed by '"'     lines terminated by '\n' from   table1; load data infile 'output.csv'   into table table1   fields terminated by '\t' enclosed by '"'   lines terminated by '\n'; 	0.647208059073086
8994821	17524	how to find certain hex values and char() values in a mysql select	select *  from `mywordtable`  where `definition`  like concat('%',char(128),'%'); 	0
9014202	36761	how generate a set of integers in mysql	select a.slot+1 from my_table a left join my_table b on (a.user = 1 and b.user = 1 and a.slot = b.slot - 1) where b.slot is null and a.slot < 100 order by a.slot limit 1 	0.00615977052434741
9030155	1302	mysql between dates	select coloums  from bilty left join runningexp on bilty.bilty_no=runningexp.bilty_no  where bilty.vehicle = '$vehicle'           and        date(bilty.date1) between date('$start') and date('$end') order by bilty.bilty_no 	0.0184891074909264
9037683	16634	segmented group in mysql	select       min( prequery.id ) as startidofgroup,       prequery.n,       count(*) as cnt    from       ( select yt.id,                yt.n,                @commongroup := @commongroup + if( @lastnvalue = yt.n, 0, 1 ) as common,                @lastnvalue := yt.n as justaplaceholder            from               yourtable yt,               ( select @commongroup := 0, @lastnvalue := 0 ) sqlvars ) prequery    group by       prequery.n,       prequery.common    order by       startidofgroup 	0.352414168922611
9039190	22367	select all ids from a mysql table by a user level and store the number of ids per level in an array?	select   user_level,count(user_id) usercount from     users  group by user_level; 	0
9041476	38578	combining a large number of conditions in sqlite where clause	select [whatever] from [sometable] st, [idtable] it where st.id = it.id 	0.0889426979850602
9065176	9033	sorting (or usage of order by clause) in t-sql / sql server without considering some words	select * from #test order by case when test like 'the %' then substring(test, 5, 8000) else test end 	0.788826241050974
9072028	7277	t-sql multiple order by clauses	select    top(5) *  from    [db].[dbo].[schedules]  where    (datepart(hour, [arrival]) >= datepart(hour, getdate()))   order by    abs(      (datepart(hour, [arrival]) - datepart(hour, getdate()))*60 + datepart(minute, [arrival]) - datepart(minute, getdate())      ),   [arrival] 	0.457867198150343
9079665	16713	sql statement to get the records with max(property) of a group	select t1.rv, t1.mv, t1.datetime, t1.rawv from mytable t1   join (select rv, mv, max(datetime) datetime from mytable group by rv, mv) t2     on t1.rv = t2.rv and t1.mv = t2.mv and t1.datetime = t2.datetime 	0.00162559237164752
9083283	6233	mysql sum if field b = field a	select incmonth as month, sum(if(item_type in('typ1', 'typ2'), 1, 0)) as 'total sales' from tester group by incmonth 	0.00153519872317788
9087363	2923	format date in select * query	select *, date_format(date, "%m-%d-%y") as date from my_table; 	0.075725694022502
9093431	16003	good way to get count of children?	select p.id,        p.name,        count(c.id) as children_count from parent p left join children c on p.id = c.parent group by p.id 	0.00418458873533059
9102551	7193	putting 2 views into 1 view in postgres	select view1.breakfastid as breakfastid, view1.eggs as eggs, view2.eggs as eggs2, view1.toast as toast, view2.toast as toast2 from view1, view2 	0.00577837792710816
9104560	25525	postgresql query - finding presence of id in any field of a record	select count(id) from usertools where toolid = @desired_tool_id 	0
9110749	31685	getting the sum two columns from two different tables	select     t1.p_id, t1.cost, t2.amount from     (select         details_pupil_id as p_id, sum(details_cost) as cost      from         edinners_details      group by         details_pupil_id) t1,     (select         payment_pupil_id as p_id, sum(payment_amount) as amount      from         edinners_payments      group by         payments_pupil_id) t2 where     t1.p_id = t2.p_id union     select         details_pupil_id, sum(details_cost) cost, 0     from         edinners_details     where         details_pupil_id not in (select distinct payment_pupil_id from edinners_payments)     group by         details_pupil_id union     select         payment_pupil_id, 0, sum(payment_amount)     from         edinners_payments     where         payment_pupil_id not in (select distinct details_pupil_id from edinners_details)     group by         payment_pupil_id 	0
9114928	21895	select row with distinct value and max date	select t.id, s.id2, s.somedate  from testme t    join      ( select id2, max(somedate) as somedate        from testme        group by id2     ) s      on  s.id2 = t.id2      and s.somedate = t.somedate; 	0.000263579431993992
9131644	35059	sql gaps in data- enroll date and disenroll date 'active_members'	select  client, min( enroll_date) [registered date],          case when (select 1 from big_pink.enrollmenthistory  where  disenroll_date is null) =  1         then null          else max (disenroll_date)         end [end date], count(*) as n from    big_pink.enrollmenthistory  where   sub_client_cd = 'b01'  and     policy_holder_id = 'bis355702848' and suffix_id = 'e'; group by client 	0.00384416151110647
9132348	14282	joining multiple large tables	select t1.a, t1.b into t4 from t1 join t2 on t1.a = t2.a and t1.c = t2.c join t3 on t1.a = t3.a and t1.c = t3.c where t3.e / t2.d < x 	0.0741289747127767
9133569	37431	mysql - change return value if select statement returns nothing	select coursecode from course where coursename='?' union all select 'not applicable' where not exists (     select coursecode from course where coursename='?' ) 	0.173828054740243
9152530	20993	sql join for partly overlapping data	select coalesce(t1.date, t2.date, t3.date) as date,        qtyt1,        qtyt2,        qtyt3 from   t1        full join t2          on t1.date = t2.date        full join t3          on isnull(t2.date, t1.date) = t3.date 	0.136302872726987
9165466	6679	find groups of data that could have a change in a second related column	select column1 from yourtable group by column1 having count(distinct columns2) > 1 	0
9166865	409	three tables, get all results from 2th and 3th tables accordingly to first table (mysql)	select ucr.*, u.*, ua1.* from users_community_relations ucr left join users u   on u.user_id = ucr.user_id left join users_avatar ua1   on ua1.user_id = u.user_id left join users_avatar ua2   on ua2.user_id = u.user_id and ua2.avatar_id > ua1.avatar_id where ua2.avatar_id is null 	0
9191423	28667	mysql select random from two rows	select    * from  ( select   * from   tablefile order by   uploaded_on_date desc limit 30 union select  * from   tablefile order by   view_count desc limit 30 ) order by     rand() limit 10; 	0.000225432861513933
9193290	16791	mysql order by field plus field	select       yt.id,       yt.type,       yt.left + yt.right as leftplusright    from        yourtable yt    where       yt.type <> 'day'    order by       if( yt.type = 'featured', 1, 2 ),       leftplusright  desc    limit 5 	0.0239945932132017
9200978	24196	sql group having selection	select p.pid, p.title from product p       inner join       (select p.title       from product p       group by title       having (count(p.title) > 1)) t on t.title = p.title 	0.596562685921448
9210895	6615	how can i summarize rows that occur only once?	select sum(c1) as c1, case when c1 = 1 then 'other' else device_type end as device_type from (  select  count(*) as c1,                 device_type          from stat          where stat_date = '2012-02-08'          group by device_type) a group by case when c1 = 1 then 'other' else device_type end 	8.22608884693179e-05
9213375	24260	t-sql count of 'a', 'b', and 'a or b'	select    count(*) as allfruits,    count(case when fruit = 'apple' then 1 end) as applecount,    count(case when fruit = 'orange' then 1 end) as orangecount,    count(case when fruit in ('apple','orange') then 1 end) as appleororangecount,    count(*) - count(case when fruit in ('apple','orange') then 1 end) as otherfruitcount from    mytable 	0.00511448717833464
9217209	18797	join three tables in mysql?	select    p.id,    p.name,    max(if(c.type = 'website', c.contact, null)) as 'website',    max(if(c.type = 'email', c.contact, null)) as 'email' from    person p inner join    personcontact pc on p.id = pc.person_id inner join    contact c on pc.contact_id = c.id group by p.id 	0.204339688880659
9224225	24542	oracle create view from two tables	select substr(site_id,1,6) site_id,site_name, vector   from table_a union select substr(site_id,1,6) site_id,site_name, vector   from table_b  where(substr(site_id,1,6)) not in (select substr(site_id,1,6) from table_a); 	0.0077285321049265
9226018	32346	database table join displays multiple entries of same rows when i only want one	select distinct streams.name, streams.desc, users.streamnumber from streams, users where users.streamnumber = '$_post[streamnumber]' and users.streamnumber = streams.name 	0
9234087	6889	selecting all users with minimum one order or more with mysql	select users.id, count(*) from orders inner join users on (orders.user_id = users.id) group by users.id having count(*)>=1 	0.000135595663490922
9238728	41221	mysql limiting rows in a many-to-many relationship	select  *  from    (         select  *         from    books         limit   6, 7         ) b left join          ba ba on      b.book_id = ba.book_id left join          authors a on      ba.author_id = a.author_id 	0.0426628000914946
9244907	36255	top 5 average scores?	select game_id, avg(score) scoreaverage from game_vote group by game_id order by scoreaverage desc limit 5 	0.00145372789813673
9249729	24390	sqlite limit query ignores the starting row number	select * from my_table limit 20 offset 40 	0.0039813715210964
9255526	28839	how can i use a column name as a variable to create a new column in my select statement?	select u.name, u.gender, u.age, p.rate_m, p.rate_f   from users as u inner join partners as p on u.id = p.m_id and u.gender = 'm' union select u.name, u.gender, u.age, p.rate_m, p.rate_f   from users as u inner join partners as p on u.id = p.f_id and u.gender = 'f'; 	0.025602622906565
9257139	40139	mysql result show first some products, then the rest	select id, productname, price from product order by topproduct, id desc 	0
9268156	26282	retrieve string data stored in integer field from sqlite 3 database using c#	select cast(s_id as varchar(255)) as s_id from users; 	0.000204185844269737
9270968	35344	mysql sort order by both timestamp and enum	select * from table order by date(date_estimated) desc, status desc 	0.0114639417007634
9285597	11035	sql: compare row with previous row based on a specific condition	select id_num, delivery_type from (select id_num, delivery_type,              row_number() over (partition by id_num                                 order by created_date desc) as rn       from demo) where rn = 1 and delivery_type = 2 minus select id_num, delivery_type from (select id_num, delivery_type, count(*) as rec_count       from demo       where delivery_type = 2       group by id_num, delivery_type       having count(*) > 1) 	0
9289992	10563	select without group by sql	select u.userid, u.username, f.verified, f.frienduserid from friends f join aspnet_users u on u.userid=f.userid where f.frienduserid='3d1224ac-f2ad-45d4-aa84-a98e748e3e57' union  select u.userid, u.username, f.verified, f.frienduserid from friends f join aspnet_users u on u.userid=f.frienduserid where f.userid='3d1224ac-f2ad-45d4-aa84-a98e748e3e57' 	0.268225192801886
9293093	15303	sql joins across multiple tables	select count(sa.option_id) as answer , so.option_label from (select a.option_id       from survey_answer a       join users u on a.uid = u.uid and u.gender='f'       where a.record_date>='2011-09-01' and              a.record_date<='2012-08-01') sa right join survey_question_options so          on sa.option_id = so.option_id where so.question_id=24 group by so.option_label order by so.option_id asc 	0.215073763744116
9311198	34764	sql union for xml name output column	select (     select id, name from (         select id, name          from xmltest          union         select id, name          from xmltest  ) a for xml path ('accountdetails'), root ('root') ) as xmloutput 	0.124917970896582
9324285	17385	display leaves status for 31 days	select   u.*,   if(1 between dayofmonth(from_date) and dayofmonth(to_date), 'l', null) '1',   if(2 between dayofmonth(from_date) and dayofmonth(to_date), 'l', null) '2',   if(3 between dayofmonth(from_date) and dayofmonth(to_date), 'l', null) '3',   if(31 between dayofmonth(from_date) and dayofmonth(to_date), 'l', null) '31' from test.user u   join `leave` l     on u.id = l.user_id 	0.000127560647696523
9329678	36898	sql search query ,how to assign weight to each input parameters and how to order the results by weight of input parameters,	select * from [car] where make = @make or        city = @city or        minprice >= @minprice or        maxprice <= @maxprice order by        case when make = @make then 3 else 0 end +        case when city = @city  then 2 else 0 end +        case when minprice >= @minprice then 1 else 0 end +        case when maxprice <= @maxprice then 1 else 0 end       desc 	0
9330151	35095	select x items from every type	select id, name, type   from (   select t1.*, count(*) cnt from table t1     left join table t2       on t2.type = t1.type and t2.id <= t1.id     group by       t1.type, t1.id   ) t where cnt <= 10; 	0
9335363	21848	sql case in where clause to select item	select      b.prig from tirr tr join bud b      on tr.id = b.id where tr.salesmen = @salesid and ((b.call = '55' and b.syst = 1) or b.call <> '55') 	0.564385129436365
9336635	1717	select row with highest number of referring rows	select videos.video, count(views.ip) as views from videos join views on videos.video = views.video group by video.video order by views desc limit 1 	0
9340853	8767	random sub-sorting records	select a.* from         tablex as a    join         tablex as b      on  b.type = a.type      and b.id <= a.id  group by        a.id order by       count(*)     , a.id 	0.0104316721674844
9350010	7591	mysql query over 3 tables	select t.tourname, count(tc.scheduleid) as numtickets from tour t  inner join schedule s on t.tourid = s.tourid inner join ticket   tc on s.scheduleid = tc.scheduleid group by t.tourid, t.tourname 	0.18743400876059
9350679	22644	searching letter in database records / mysql	select *  from ...  where name regexp ('([a-z]..$|[a-z].$|[a-z]$)') 	0.00320631035689168
9352215	1248	mysql select row dateandtime > now	select count(*) from table where unix_timestamp(action_time) < unix_timestamp(now()); 	0.0165893426159387
9353145	27721	sql query select and ordering all from same table with key/value pairs	select a.resource_no, a.value webcategory, b.value location  from      resources a left join resources b on a.resource_no=b.resource_no and b.key='location' left join resources c on a.resource_no=c.resource_no and c.key='order' where a.key = 'webcategory' and a.value='dog' group by resource_no order by c.value 	0
9355379	19378	display a date format from mysql database	select date_format(current_timestamp(), '%m %e, %y %h:%i%p'); 	0.000196332549831847
9355478	18185	two select statements in one query	select `age` from `users` where `userid`=   (select `id` from `second`      where `second`.`name` = 'berna') 	0.0309405414215895
9358907	16272	find a value after a point or before apoint	select         floor(23.25) from dual select 23.25 - floor(23.25) from dual 	0.00417076815020201
9366137	41067	if null, return multiple values	select myval  from mytable  where number = @number or (not exists(select * from mytable where number = @number) and number = 999) 	0.0125346138691715
9366197	29971	select the 3 highest values using php mysql query	select sum(value) as sumoftop3values from (     select value     from table     order by value desc     limit 3 ) as sub 	0.000824177704145705
9366360	2372	sql calculate sum of part of the data	select date, subs, unsubs, (@csum := @csum + subs - unsubs) cumulative from table, (select @csum :=0) c order by date 	0.000276144031877447
9367740	14928	order by on multiple conditions	select * from table order by      price desc,     date asc limit 1 	0.14052654550144
9370430	5465	sql query getting name and desc from one main table and two sub tables.	select city_geo.geography_name as city,state_geo.geography_name as state, zip_geo.geography_name as postalcode from zip_to_city zc, zip_to_state zs,  geoinfo city_geo, geoinfo state_geo, geoinfo zip_geo where zc.city_id = city_geo.id and state_geo.id= zs.state_id and zip_geo.id = zc.zip_id  and zip_geo.id = zs.zip_id and zip_geo.name = ? 	0.000574514379740853
9396516	9044	mysql duplecating results	select d.quantity,         d.productid,         p.productname,         d.unitprice,         d.discount from   **customers as c,**         orders as o,         order_details as d,         products as p where  o.orderid = '10248' and    o.orderid = d.orderid and    d.productid = p.productid 	0.278156052494743
9398502	38006	microsoft access query - not returning all data	select * from table1 left join table2 on table1.flp = table2.flp left join table3 on table1.flp = table3.flp; 	0.736340201255484
9401459	20143	select multiple items which match mapping table more then once	select questions. * , posts.post, posts.id as post_id, posts.created, users.id as user_id, users.username, users.rep from questions left join posts on questions.id = posts.question_id left join users on questions.user_id = users.id left join topic_mapping on questions.id = topic_mapping.question_id where topic_mapping.topic_id in (49,50) group by questions.id having count(distinct topic_mapping.topic_id) = 2 limit 0 , 30 	0
9424583	23485	mysql select distinct with additional column in result set	select id, name, min(price)from deals_unsorted group by name 	0.0333572090742372
9431914	35635	gaussian random distribution in postgresql	select     random() +      random() +      random() +     random() +      random() +      random() +     random() +      random() +      random() +     random() +      random() +      random(); 	0.0994813500840043
9435096	40500	sql select multiplicity of items in union	select id, count(id) as multiplicity  from (     select id from foo where ...     union all     select id from bar where ...     union all     select id from baz where ... ) as tablestogether group by id 	0.0152515403169954
9435459	6775	view that accesses two databases	select d1.productid, d2.productinfo from database1.schemaname.table d1 join database2.schemaname.table d2 on d1.key=d2.key 	0.0256841800976114
9437526	37612	is it possible to get all rows from a table and apply conditions using php?	select sum(if(expire == 1, 1, 0)) as expired,  sum(if(expire == 0, 1, 0)) as notexpired  from table; 	0.000150863076176986
9469403	7363	select count() when field is unique	select giftsource, language, renew, type, count(*) ;   from <whatever tables and joins you need> ;   group by giftsource, language, renew, type 	0.015589192381102
9485829	28055	how to get a substring of variable size for each row in mysql?	select substring(subcolumn, 9,5) as field1,      substring(subcolumn,  24) as field2      from (                 select substring(column, 1, locate('\n',column,15)) as subcolumn         from table ) as x 	0
9488768	38716	mysql - select 3 highest values and sort alphabetically	select *                     from   ( select keyword, hits      from table      order by hits desc            , keyword asc         limit 3   ) tmp order by keyword 	0.000188376385944496
9497189	18858	group_concat pulling out empty result with delimiters	select p.id, group_concat(s.size1) size1,  group_concat(if (s.size2 ='', null, s.size2)) as size2, p.prod  from products p join stock s on s.prodid = p.id 	0.260826310822032
9497364	15504	multiple sub queries	select created_date,        count(field1) enrolled,        count(case field1 when 'e-mail' then 1 end) enrolled_as_email,        count(case field1 when 'cell phone' then 1 end) enrolled_as_cell,        (select count(*)         from tbl_transactiondishout d         where d.created = c.created_date and               d.dishoutresponsecode = '0000') deals_redeemed from tblcustomer c group by created_date order by created_date 	0.545061438360091
9526550	23050	rename column names in mysql	select concat('alter table ', table_name, ' change ', column_name, ' ', replace(column_name, '/', ''), ' ', column_type, ';') from information_schema.columns where table_schema = 'mydbname' and column_name like '%/%'; 	0.00249444362670396
9546114	28526	mysql: find string with most matching starting characters	select name from names where 'name111someignorechar' like concat(name,'%') order by length(name) desc limit 1 	8.54865869597549e-05
9563421	30501	sort months array by position	select `date` from `events` where `status`=1 order by `name`" group by month(`date`) 	0.00303077721097339
9569560	6981	sql detecting partially duplicated rows	select id     from yourtable     where x in ('yes', 'no')     group by id     having count(distinct x) = 2 	0.0225659874552751
9593185	15452	different between two tables	select id from [tableb] where not exists(select id from [tablea] where [tablea].id=[tableb].id) 	0.000880744446768156
9601811	8924	limiting a mysql result	select t1.name,t1.subject,t1.grade from sometablename t1 inner join (select name,subject,max(counter) as counter              from sometable              group by name,subject) t2 on t1.counter = t2.counter 	0.265431787122083
9626601	23072	sql & multiple tables and outputting data but also where data does not exist	select * from documents d left join user-readdoc ud on d.docid = ud.docid 	0.0463540792993252
9632737	21584	getting data from 2 different mysql tables	select tab1.*,tab2.* from table1 tab1 join table2 tab2 on tab1.id=tab2.id where tab1.username=$username 	0.000122850708277262
9654269	35006	selecting distinct column name with respectives values	select p_id, userid, min(the_date) from table group by p_id, userid 	0.000587717807003816
9664544	36909	distinct sum with many-to-many relationships	select  t2.name as t2name ,t2.orders as t2orders ,t1sum.price as t1sumprice ,t1.price as t1highestprice ,t1.name as t1highestprice_name from t2 t2 inner join (     select rel.t2id         ,rel.t1id         ,row_number()over(partition by rel.t2id order by price desc)as pricelist         ,sum(price)over(partition by rel.t2id) as price         from t1 t1          inner join            (select t1id, t2id              from relation             where not exists (select null from relation test where test.t1id = relation.t1id                               and test.t2id < relation.t2id)         )         rel on rel.t1id=t1.id )as t1sum on  t1sum.t2id = t2.id and t1sum.pricelist = 1 inner join t1 t1 on t1sum.t1id=t1.id 	0.137066939451141
9678573	36659	get previous from max value	select max(card_no),vehicle_number from wbg.wbg_01_01 where card_no < (select max(card_no) from wbg.wbg_01_01 group by vehicle_number) group by vehicle_number 	0
9695952	19310	sql filtering based on calculated time slots	select projectorname from projectors where not exists     (select 1 from projectorreservations    where projectors.projectorname = projectorreservations.projectorname    and (projectorreservations.starttime < {end_time}    or projectorreservations.endtime > {start_time})) 	0.00123508184300688
9720907	7106	select rows where day number is less than given threshold	select * from tablea    where  dayofyear(datecol) < 50  select * from tablea  where  dayofyear(datecol) between 50 and 100  	0
9721904	23263	mysql - select just the highest count from each different column type	select user,max(score)  from mytable  group by user 	0
9733408	38059	sql query to find all products by user and division?	select product_id, product_name and division_id   from products as p  where exists (                select *                   from userproducts as u                 where u.division_id = p.division_id                       and u.product_id = -1               ) union select product_id, product_name and division_id   from products as p  where exists (                select *                   from userproducts as u                 where u.division_id = p.division_id                       and u.product_id = p.product_id               ); 	0.00128160229327231
9734891	18708	retrieve random data	select top 2 starttime, endtime from data order by newid() 	0.0030336160433437
9741891	13672	select row from table but exclude row that has id already in another table	select videos.*  from videos      left join favs on videos.videoid=favs.videoid where favs.videoid is null 	0
9754037	13573	mysql join with sort and group by choosing the element to display	select      evt.evt_id,     evt.name,     content.content_id,     content.content_text from t_evt as evt    inner join t_content as content      on evt.evt_id = content.content_evt_fk   inner join    (     select content_evt_fk, max(t_content.content_id) content_id       from t_content      group by content_evt_fk   ) last_content     on content.content_id = last_content.content_id     and content.content_evt_fk = last_content.content_evt_fk 	0.0016203185001914
9755562	17878	matching the beginning characters in a like clause	select * from mytable where somecol like 'harris%' 	0.0561514969742247
9769486	3889	php/mysql: hours reported, hourly rate	select sum(h.hours * hr.hourly_rate) as pay    from hours h, hour_rates hr    where h.user_id = :user_id     and h.user_id = hr.user_id and (h.date between hr.start_date and hr.end_date     and h.date between str_to_date('01,1,2012','%d,%m,%y') and str_to_date('01,1,2011','%d,%m,%y') 	0.00136580108380734
9773045	772	filter mysql table using data from another table	select distinct username, start  from login  left outer join notification on      (login.host_id = notification.host_id      and login.start = notification.event_start     and login.username = notification.info)  where      end>date_add(start,interval 12 hour)      and login.host_id=$host_id      and last=1      and login.id is null 	0.000244849226086691
9782523	30809	mysql selecting unique values	select count(distinct email) from france_data 	0.00138857378304328
9788599	13638	sql: join with substrings	select * from a   inner join b      on b.b like '%'+a.a+'%' 	0.521003590626821
9788735	10022	select different data based on the result of count	select users.id, if(count(others.id) = 0, '', count(others.id)) as c from users join other on users.id=others.user_id  group by users.id 	0
9789498	24570	how to select one record per user?	select u.id as user_id, max(h.id) as hra_id from users u       inner join hra h on u.id = h.user_id       where h.date between ? and ?       and h.done = 1  group by u.id 	0
9796078	7780	selecting rows ordered by some column and disctinct on another	select * from purchases t1 left join purchases t2 on t1.address_id = t2.address_id and t1.purchased_at < t2.purchased_at where t2.purchased_at is null order by t1.purchased_at desc 	0
9803469	39755	mysql sum grouping issue	select group as unique_id, sum(value) as totalvalue from table where group>0 group by group union select id as unique_id, value as totalvalue from table where group=0 	0.776259047090049
9814522	36186	searching multiple tables (sql)	select 'artists' originatingtable, id, name   from artists  where name like '%snoop%' union all select 'albums', id, name   from albums  where name like '%snoop%' union all select 'songs', id, name   from songs  where name like '%snoop%' 	0.123116060284562
9818784	9431	coarsening group by in sql	select case when customerid=1 or customerid=2 then '1,2'             when customerid=3 or customerid=4 then '3,4'                                               else customerid        end      , sum(amout) from table group by case when customerid=1 or customerid=2 then '1,2'               when customerid=3 or customerid=4 then '3,4'                                                 else customerid          end 	0.392489385150794
9822684	17332	how do i get query for products added in last 30 days (hsqldb)	select  * from    invoices where   invoicedate > dateadd('day', -30, current_date) 	0
9826993	21904	sql server distinct on earliest date in a timestamp column	select name, min([last logged on date]) as [first logged on date] from audit group by name 	0.000459157672343689
9827796	33092	need assistance using a join to retrieve sums, or 0 from the right table if there is no entry present	select        bc.name,        bc.category_id,       bc.ref_id,       coalesce( bc.parent_id,bc.category_id) as which_category_id,       coalesce( bcparent.name, bcdefcat.name ) as category_name,       coalesce( bcparent.ref_id, bcdefcat.ref_id ) as category_ref_id,       coalesce(sum(bee.amount),0) as amount     from          budget_categories bc             left join budget_expected_expenses bee               on bc.category_id = bee.cat_id               and bee.group_id = 1               and bee.date between '2012-01-01' and '2012-01-31'             left join budget_categories bcparent               on bc.parent_id = bcparent.category_id            join budget_categories bcdefcat               on bc.category_id = bcdefcat.category_id    where        bc.group_id in (1,139)     group by        bc.category_id     order by        bc.ref_id asc 	0.00986796289933014
9829650	32617	how to sum items in a table if their fk appears more than once?	select fk, sum(value) from   your_table group by fk 	0
9855810	19194	mysql count maximum number of rows	select max(cnt) cnt, dept from (     select count(*) cnt, dept, c.cid     from courses c          inner join enrollment e on c.cid = e.cid     group by cid, dept ) a group by dept 	0
9867547	33871	mysql join on same table	select p.subject as parent,  group_concat(c.subject) as children  from yourtable as p  left join yourtable as c  on (p.id = c.parent_id and p.parent_id = 0)  group by p.id;` 	0.0176585012178131
9891775	18792	most common hour query?	select hour(date) as hr, count(*) as cnt from yourtable group by hr order by cnt desc limit 1 	0.000709841919649725
9910135	2949	ms sql 2008 - how do i convert xml value into a collection of rows from a ms sql table?	select    t.n.value('key[1]', 'int') as [key],   t.n.value('value[1]', 'varchar(10)') as value from @x.nodes('/root/kv') as t(n) 	0.000145036986195743
9923258	9584	mysql add row and count from diffrent table	select users.user, users.id, count (species.name) from users left join species  on users.id = species.user group by users.user, users.id order by count (species.name) desc 	0.000197821165042374
9931357	33371	sql - need a query to search messages by recipient	select mt.threadid, u.userid, u.userfullname       from messagethreads mt  inner join messagethreadusers mtcu on (mtcu.threadfk = mt.threadid) inner join users cu on (mtcu.userfk = cu.userid and cu.userid = 'usr_developer') inner join messagethreadusers mtu on (mtu.threadfk = mt.threadid) inner join users u on (mtu.userfk = u.userid and u.userid <> 'usr_developer')       where u.userfullname like '%john%'  	0.611699835258242
9939507	15086	how to show all records from a specific mysql row - except duplicates?	select distinct myrow from mytable; 	0
9942993	28153	how to write query in oracle and sql_server to get records with the most statuses?	select tenant_id, s from   (            select tenant_id,            count(*) as s,            rank() over(order by count(*) desc) as rn     from candidate     where status_id = 7     group by tenant_id   ) t where rn = 1; 	0.000535829058832639
9951785	19517	mysql select query	select * from (select * from mach_1 order by id desc  limit 10) as tbl order by tbl.id; 	0.387336905290878
9952736	12397	sql match rows based on 2 criteria	select a.id,b.security_id,a.time_to_maturity,a.price from db1 a, ( select security_id, min(time_to_maturity) as min_time_to_maturity, max(time_to_maturity) as max_time_to_maturity,     max(time_to_maturity) - min(time_to_maturity) tdiff,     ((max(time_to_maturity) - min(time_to_maturity)) * .1) + min(time_to_maturity)   from db1   group by security_id   order by security_id ) b where a.security_id = b.security_id   and a.time_to_maturity < (b.min_time_to_maturity+(b.tdiff*0.1)); 	0
9961921	17764	how to compare time with current time & display result based on that using mysql?	select shop_name,if(left(curtime(),5) between start_time  and close_time ,'open','closed') as status  from tablename 	0
9973641	35328	how to merge a query result by datetime in same table mysql?	select b.date,  sum(case when a.id=1 then b.value else 0 end) as mac1,  sum(case when a.id=2 then b.value else 0 end) as mac2,  sum(case when a.id=3 then b.value else 0 end) as mac3  from tablea a, tableb b  where (a.id = b.id) and (b.date between '2011-04-02 06:00' and '2011-04-02 06:05')  group by b.da_date 	0.000498482529630442
9974390	14918	find longest range of free ids in mysql, using a query?	select t1.doc_id,        max(t1.doc_id-ifnull(t2.doc_id,0)) as difference from `table` t1     left join `table` t2 on t1.doc_id>t2.doc_id     left join `table` t3 on (t1.doc_id>t3.doc_id and t3.doc_id>t2.doc_id) where t3.doc_id is null group by t1.doc order by difference desc 	0
9976429	5876	join with multiple rows for fulltext search	select nodeid, name, sum(fulltextrelevsum) as fulltextrelevsum from group by nodeid 	0.55079938838543
9977644	5292	retrieve venues where there are no events on that day only	select venues.* from venues left join events on events.venue_location = venues.id  and start_datetime >= '$date_start_selected' and end_datetime < '$date_end_selected' where events.venue_location is null group by venues.venue_name 	0
9982039	11494	mysql finding the most expensive in each zip code	select       t.name, t.city, t.zip_code, t.price from          ( select zip_code               , max(price) as price           from products           where state = 'nj'           group by zip_code        ) as tm      join         products as t             on  tm.zip_code = t.zip_code              and tm.price = t.price where          t.state = 'nj' 	0.000164951918417697
9983402	35124	sql joins displaying only available times	select * from availability where not exists (     select 1     from appointment     where appointment.appointmenttime = availability.availabilitytime         and appointment.employeeid = availability.employeeid ) 	0.00456464463753251
9989046	2798	how to read current value in sql	select    p1.title, pj.total from     pizza p1 join     (     select         p2.title title, count(p2.id) total     from pizza p2      where p2.title like '%pizza%' and p2.title like '%store%'     group by p2.title    ) as pj on p1.title=pj.title 	0.00404082330674523
9991950	28539	a sql query from oracle database	select column1, column2 from mytable  group by column1, column2 having count(*) = 1 	0.128334831073017
9993234	35982	sql query repeat	select  car_id as clm_car_id,          car_image_url as clm_picture_url,         user_agent_name as clm_username from    car         inner join users             on car_user_id = user_id         left join         (   select  img.*             from    car_image img                     inner join                      (   select  min(image_id) as image_id                         from    car_image                         group by car_image_car_id                     ) as maximg                         on maximg.image_id = img.image_id         ) as img             on img.car_image_car_id = car_id; 	0.247788078094206
9994293	247	mysql weighting unique fields by external values	select case id  when 1 then 300 when 2 then 100 when 3 then 200 end as weight  from tab  order by weight; 	0.00609536400991531
9996472	40338	sql - how to find all linked ids from a table	select linked_id   from data  start with id = :1 connect by nocycle prior id = linked_id         or id = prior linked_id union select id   from data  start with linked_id = :1 connect by nocycle prior id = linked_id         or id = prior linked_id union select :1 from dual 	0
9998174	1696	return sql max, with other data in table	select   r.resourceid,   r.netbiosname0,   l.name0,   l.lastlogon0 from table2 as r outer apply (   select top (1)      name0,     lastlogon0   from table1 as l   where l.resourceid = r.resourceid   order by numberoflogons0 desc ) as l 	0.00175362988314576
10017127	10838	assigning a local variable from a table using a join statement	select [type] from dp d     join dtxr x on d.programid = x.programid    where dtxr.qei = @p_qei 	0.509055632441428
10018395	17968	how to quickly analyze a postgres database	select oid::regclass, pg_size_pretty(pg_total_relation_size(oid))   from pg_class   where relkind = 'r'   order by pg_total_relation_size(oid) desc   limit 20; 	0.546928478367781
10019744	19562	sql join two tables with one-to-many associative array?	select   [id],   [created_by],   [field_number1] = sum(case when [field_number] = 'field_number1' then [field_value] else 0 end),   [field_number2] = sum(case when [field_number] = 'field_number2' then [field_value] else 0 end) .... from wp_rg_lead inner join wp_rg_lead_detail on wp_rg_lead.id = wp_rg_lead_detail.lead_id where wp_rg_lead.form_id = '9' and wp_rg_lead.payment_status = 'approved' 	0.131027575948576
10028431	31901	how to select count of ranges from mysql table?	select      count(case when point between 0 and 100 then 1 end) as count0_100,      count(case when point between 101 and 200 then 1 end) as count101_200,      count(case when point between 201 and 300 then 1 end) as count201_300,      ... from     t_poits 	7.5296672998968e-05
10053674	28024	search three columns	select * from `job`  where c_name = 'john doe' and (customer_ref like '%do%' or order_details like '%do%') 	0.0374507864126357
10075652	2838	how to make multidimensional array from database query	select call_time, call_type, count(*) as num_by_type from db group by year(call_time), month(call_time), day(call_time), call_type. 	0.13262584542499
10081819	3013	mysql group by yearweek get first and last doesn't work	select yearweek(date, 1) as ignore, min(date) as date 	0.00328601930421439
10085947	40283	linq group by and max()	select  cs.site_name ,         max(ed.effectivedate_date) from    [wapmaster].[factsheets].[effectivedate] ed ,         [wapmaster].[configuration].[site] cs where   cs.site_id = ed.effectivedate_siteid group by cs.site_name from e in wapmaster.factsheets.effectivedate join c in wapmaster.configuration.site on c.site_id equals e.effectivedate_siteid group e by c.site_name into r select new { sitename = r.key, effectivedate = r.max(d=>d.effectivedate_date)} 	0.441086932422856
10109229	15368	counting from field in table then updating to a different field in a different table	select users.*, count(timetable.username) as num_slots from users left join timetable     on users.username = timetable.username group by users.id 	0
10111153	23457	mysql where ... in ... and where ... in ... should only match on same index	select *  from users where (firstname, lastname)        in ( ('luke', 'skywalker')           , ('foo' , 'bar')           , ('tom' , 'turner')          ) ; 	0.0480819523273438
10127788	19443	sql query that involves or won't return results if one of the tables empty	select s.* from section s left join sectioncompany scom on (s.id = scom.sectionid) where ((s.restricted = 0 ) or (s.restricted = 1 and scom.companyid = $companyid)) 	0.0351842987354311
10137132	18936	mysql query order asc starting from 1 then show all with zero	select * from table order by val = '0', val 	5.47839519644885e-05
10144006	1076	pulling data from a different table if pertaining data is not available in a table	select     [month], isnull([forecasted avg. temperature], [actual avg. temperature]) as temperature  from     table2 left outer join table1 on table1.[month] = table2.[month] 	0
10167391	39961	sql - query to find the number of entries in a given category	select category, count(1) from table group by category 	0
10184173	19088	mysql select with 2 different substrings and single where from 1 column	select right(productid, 2) as 'a', substring(productid,1,2) as 'b', productid  from products  where `group`='$one'  group by productid having   a = 'aa'    and b like '$two' 	0
10187161	6799	sql- how to find the top 1 row?	select account, min(dt_effective) from your_table group by account 	0.000192761422872239
10189528	23538	renaming column names to blank in select	select column1 as [ ] 	0.00216511578906256
10197035	30271	sum columns by hour (using datetime column)	select datepart(hour,mydate), sum(offered) from mytable group by      datepart(hour,mydate),      dateadd(d, 0, datediff(d, 0, mydate)) 	0.000364018794643643
10200102	12793	date_format and sort by date	select date_format(`date`, '%d-%m-%y') as date_formatted from mytable  order by `date` desc 	0.170826602304615
10205018	40126	sql replacing a field with specific text	select 'longest time' as status, name, longname, max(starting) from one union select 'shortest time' as status, name, longname, min(starting) from one; 	0.031317962653043
10206149	33941	ordersubquery combined with second table	select `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`, `prod_combined`.`link` from `prod_combined`  inner join `prod_history` on prod_combined.sku = prod_history.sku where prod_history.insert_date >= subdate(curdate(), interval 31 day)    and prod_combined.aktiv = 1 group by `prod_combined`.`sku`, `prod_combined`.`titel`, `prod_combined`.`preis_vk`, `prod_combined`.`link` order by sum(prod_history.number_of_orders) desc limit 5 	0.00709882566193018
10225503	14142	sum of different column in sql	select      itemcode,     sum(case selectedsupplier         when 1 then supplier1price         when 2 then supplier2price         when 3 then supplier3price     end) as supplierprice from canvasstable group by itemcode 	0.00289680734245965
10230438	25578	mysql - join 2 tables	select u.*, b.balance, b.date from users u join balance b on u.id = b.userid where b.date = (select max(date) from balance where userid = u.id); 	0.0900297638744929
10230741	10124	brain boiling from mysql - how to do a complicated select from multiple tables?	select * from [users] where [id] not in  (select replace(id,'pid_','') from groups where group_name='group1') 	0.0291097943035276
10237212	26574	getting the total number of identical items in a table in mysql	select upc, sum(count) as count from yourtable group by upc 	0
10238407	20949	sqlite: query same table twice with two different "where"	select year,          sum(case when flow = 'grant' then finance else 0 end) as grant_total,          sum(case when flow = 'loan' then finance else 0 end) as loan_total  from your_table   group by year 	0.00135410424221404
10245428	21344	mysql sly select	select f.name, f.value, f.date from (    select id,name,max(date) as dat from tablename group by name ) as x inner join tablename as f on f.name = x.name and f.date = x.dat; 	0.234738910580471
10245469	6019	selecting field from referenced row of foreign key to same table	select t2.field_you_want  from your_table as t1 join your_table as t2 on t1.foreign_key = t2.primary_key where ... 	0
10254166	8708	searching for data that can be in two different column (query/design)	select match_id from matches where team1 = 'arsenal' or team2 = 'arsenal'; 	0.00162202487099078
10257337	25987	sorting varchar fields for mysql database	select * from t order by substring(     team_total, locate('for', team_total) +          if(locate('for', team_total) > 0, 4, 7))+0 desc 	0.06681442078299
10266993	33962	select in sql with id parameter	select t.id, t.name, g.name  from table t     join genres g on t.genre = g.id 	0.132234223675706
10274114	10715	combining two selects next o each other, not on top of the other	select id,name,surname from table_1 inner join table_2 on table_2.id=table_1.id where table_1.id = 2 	0
10278468	22522	comparing mysql timestamps	select * from (`payments`) where `lastupdated` >= date_sub(now(), interval 15 day) 	0.0163614332130173
10285922	36934	sql/db2 - only show rows that exists 3 or more times	select employee.lastname, employee.firstnme, emp_act.projno, count(*)     from employee          join emp_act              on employee.empno = emp_act.empno     group by employee.lastname, employee.firstnme, emp_act.projno     having count(*) >= 3 	6.75332503110544e-05
10295047	23306	how do i replace the same thing in multiple columns within a select statement in sql?	select     replace(firstcolumn, '"', '\"'),     replace(secondcolumn, '"', '\"') from testtable 	0.00842658929653305
10297437	29922	mysql: checking range time conflicts	select (count(*) = 0) as available from batchroutine_regular where       teacherid = 1001   and class_day = 'sunday'   and (        (class_start <= maketime(11,00,00) and class_end >= maketime(11,00,00))     or (class_start <= maketime(13,00,00) and class_end >= maketime(13,00,00))   ) 	0.0241575811013854
10304438	15638	select all comments from friends - mysql query	select * from comments c inner join friends f on c.member_id = f.member_id where f.member_id_friend = [current user id]   and c.video_id = [desired video id] 	0.000228132655763506
10320407	31662	selecting the highest seq number by nested joining	select      * from  (     select          t1.clid, t1.seqid, t3.bal,          rownumber = row_number() over (partition by t1.clid order by t3.bal desc)     from          clientseqtable t1     inner join         seqbranchtable t2 on t2.seqid = t1.seqid     inner join         balancetable t3 on t3.balid = t2.balid ) t where     t.rownumber = 1 	0.00021716251723436
10324597	34131	make mysql answer how many names are in table	select name, count(1) as count from test group by name 	0.00345773532246553
10324773	8813	how to match unique id from the different table in database and retrieve data according to that unique id in java?	select user.userid, user.name, user.lastname, user.dob, points.gamepoints from user, points where user.userid = points.userid    and (user.name = ? or user.lastname = ?) 	0
10348778	38767	creating a pseudo linked list in sql	select    id,    location,    order_id,   lag(id) over (order by order_id desc) as next_id from your_table 	0.416851168859882
10353969	93	how can i select from list of values in oracle	select distinct column_value from table(sys.odcinumberlist(1,1,2,3,3,4,4,5)) 	0.000606030316038703
10356083	16921	mysql - retrieve correct values using coalesce?	select mem.member_name, g.* , coalesce(f.flower_color, b.bear_color) as color from members mem inner join general g on mem.member_id = g.member_id left join flowers f on g.gift_item_id = f.flower_id and g.gift_item = 'flower' left join bears b on g.gift_item_id = b.bear_id and g.gift_item = 'bear' where g.month='june' 	0.11712067432581
10357203	22132	selecting few columns of a result set as xml	select      id, name,     (select phone, address      from dbo.tmp_user u2      where u2.id = u1.id      for xml path('data')) as 'extradata' from        dbo.tmp_user u1 	0.000280122152735125
10382384	34349	t-sql: how to use min	select id, min(someval) from [tablename] group by id 	0.447665901262283
10385669	11668	count using two (or more) columns	select c.class_name as 'class name', s.child_gender as 'gender',        count(s.student_id) as 'count' from student s inner join classregister cr on s.student_id = cr.student_id  inner join classes c on cr.class_id = c.class_id group by s.child_gender, s.class_id, c.class_name order by c.class_name 	0.0152211406042981
10386998	35154	query to extract highest value for each id submitted	select * from (  select *, row_number() over(partition by peh_pmt_id order by eh_id desc) corr         from employer_history          where eh_pmt_id in (131,3725)) t1 where corr = 1 	0
10392680	33120	sql query: using distinct/unique and sum() in one statement	select   name,   max(level),   class,   sum(kills),   sum(deaths),   sum(points),   sum(totaltime),   sum(totalvisits),   characterid from   characters where   name like '$value%' or characterid like '$value' group by   name,   class,   characterid order by   name asc ; 	0.382054615734368
10398143	5840	mysql, select column value when using group by and having	select asset_property.asset_id, category_name, ( case property_id         when 1 then property_value        else 0   end ) from asset_property left join asset      on asset.asset_id = asset_property.asset_id left join category      on category.category_id = asset.category_id group by asset_property.asset_id having count(asset_property.asset_id) <= 2 	0.0518310776726306
10400950	40528	sql select statement to pull data from multiple tables with foreign keys and associative relationships	select c.campusname,u.uniname,c.campusaddress, s.specname, ic.codenumber, p.projectname from campuses c inner join universities u on u.iduni = c.iduni inner join camousspecialization cs on cs.idcampus = c.idcampus inner join speicialization s on s.idspec = cs.idspec inner join projectspecialization ps on ps.idproject = s.idspec inner join projectindustrycode pi on pi.idproject = ps.idproject inner join industrycode ic on ic.industrycode = pi.industrycode inner join projects p on p.idproject = ps.idproject 	5.72795056280375e-05
10401116	2690	mysql alter all columns in table	select id as 'peopleid' from people 	0.000979484854942517
10402981	27850	need oracle sql returns 1 row when 0 rows are selected	select name  from employee  where id=1 union all select 'empty' from dual where not exists (select 1 from employee where id=1) 	0.00551640732739223
10412360	36918	count multiple row values in the same query, mysql	select model_id, type_id, model_name,  sum(case when device_status=2 then 1 else 0 end) as device2,  sum(case when device_status=3 then 1 else 0 end) as device3,  sum(case when device_status in (2,3) then 1 else 0 end) as device2device3  from devices  left join models on models.model_id = devices.type_id  where device_status = 2 or device_status = 3  group by type_id 	0.000214312394255329
10439122	4983	select count(*) from select	select count(*) from  (   select distinct a.my_id, a.last_name, a.first_name, b.temp_val    from dbo.table_a as a     inner join dbo.table_b as b     on a.a_id = b.a_id ) as subquery; 	0.0126382339178331
10443462	27654	how to get the numeric part from a string using t-sql?	select left(@str, patindex('%[^0-9]%', @str+'.') - 1) 	0.000613741461666534
10446484	8769	sql group by but use the most recent record?	select      gd.gradebookdetailid,      g.subjectcode,      g.description,      g.unitsacademic,      g.unitsnonacademic,      gd.grade,      gd.remarks,      g.facultyname,      str_to_date(g.dateapproved, '%m/%d/%y %h:%i:%s') as 'dateaproved' from      gradebookdetail gd inner join      gradebook g on gd.gradebookid=g.gradebookid  where      g.dateapproved is not null and      g.gradebooktype='final' and      studentidnumber='2012-12345' and      not exists (         select 1 from gradebook g2          where              g2.gradebooktype = 'final' and              g2.dateapproved is not null and              g2.studentidnumber = g.studentidnumber and              g2.studentcode = g.subjectcode and             g2.dateapproved > g.dateapproved     ) order by g.subjectcode asc 	0.000347285674552513
10447446	15394	retrieving rows from mysql table using groupby	select     a.dblversion,    a.sname,    a.fcompleted,    a.ixlastmodifiedby,    a.dtcreatedat,    a.dtlastmodifiedat,    a.fstatus  from     tblechecklisttemplateversion a join (     select          ixtemplate,         max(dblversion) as dblversion      from          tblechecklisttemplateversion      group by          ixtemplate) as b on      a.ixtemplate=b.ixtemplate and a.dblversion=b.dblversion 	0.000946841085815961
10453114	1855	sql statement workflow	select name, orderid, product, price from orders where orderid in ('row1', 'row2', 'row3', ...); 	0.680060442691199
10456326	25830	getting the rows returned by a subquery as columns of the original	select students.studentid,         students.name,         schools.name,         mintitle as workshop1,         ( case             when mintitle = maxtitle then null             else maxtitle           end )  as workshop2  from   students         join school           on students.schoolid = schools.schoolid         join (select studentid,                      min(title) as mintitle,                      max(title) as maxtitle               from   workshop w                      join workshopregistration wr                        on w.workshopid = wr.workshopid               group  by studentid) w           on w.studentid = stuents.studentid 	5.45266574526061e-05
10458976	3954	how do i place threads at the top(bump) based on last user post?	select distinct forum.* from forum        left join replies on           forum.id = replies.thread_id   order by coalesce(replies.reply_timestamp, forum.thread_timestamp) desc     limit 12 	0
10460755	16148	comparing in sql and sum	select    month    ,year    ,subcategory    ,privatelabel    ,sum(price) as [total sales] from    a inner join b ... where    any where clauses  group by    month    ,year    ,subcategory    ,privatelabel 	0.0998227382328204
10467990	8036	joining table on social one with hyphens, and the other without	select <whatever> from employee e join      degree d      on e.ssn = cast(replace(d.ssn, '-', '') as int) 	0.00186578937695563
10475403	8430	sqlite returns 0 rows	select skill_name, character_name, cb_id, cb_id2  from characterbasics, characterskills  where  characterbasics.character_name = 'joe' and characterbasics.cb_id =  characterskills.cb_id2 	0.0757542006832335
10482033	495	grouping by shopname count different type of customer(membership)	select s.shopname,        count(c1.customerid) as 'silvermember',        count(c2.customerid) as 'goldmember',        count(c3.customerid) as 'lifemember' from shop s left outer join customer c1 on c1.shopid = s.shopno and c1.membershiptype = 'silvermember' left outer join customer c2 on c2.shopid = s.shopno and c2.membershiptype = 'goldmember' left outer join customer c3 on c3.shopid = s.shopno and c3.membershiptype = 'lifemember' group by s.shopname 	0.00444055469910912
10491142	28397	how to create a contacts page properly?	select distinct contacts.contact_id, accounts.full_name from contacts, accounts where (contacts.my_id = '$sid' and contacts.contact_id = accounts.user_id) or (contacts.contact_id = '$sid' and contacts.my_id = accounts.user_id) 	0.455675371962771
10532914	2479	how to use count and sum in the same query?	select count(*) as total_rows from ( select d.podetailid as podetailid, sum(d.acceptedqty) as total_acceptedqty from str_mrvdetail d  inner join str_mrvheader h on h.mrvid = d.mrvid  inner join pur_poheader ph on ph.poid = h.poid  inner join pur_podetail pd on pd.podetailid = d.podetailid where h.statusid = 4 and ph.poid = 839 and (select sum(acceptedqty) from str_mrvdetail       where str_mrvdetail.podetailid = pd.podetailid) =       (select poquantity from pur_podetail        where pur_podetail.podetailid = pd.podetailid) group by d.podetailid ) as t 	0.0138515258424233
10541895	10980	sorting so that rows with matching column do stick together	select f.*  from   feed f         inner join (select max(tm) maxtm,                            author                     from   feed                     group  by author)m           on f.author = m.author  order  by m.maxtm desc,            f.author 	0.00346535102837318
10548222	13349	how to count no of specific symbol in a row in mysql	select length('/2323/3235/4545/222/') - length(replace('/2323/3235/4545/222/','/','')) ... etc; 	0.000358113541865885
10564071	6411	sql: select all record matching value 'x', but stop when value 'y' appears	select p1.id from periods p1 where p1.value = 1 and ( select p2.value from periods p2        where p2.id<p1.id        order by p2.id desc limit 1 ) = 0 order by p1.id desc limit 1 	0
10567698	35592	querying the latest version of a row	select        c.* from          ( select parent_id                , max(id) as id           from copy_blocks           group by parent_id         ) as dc     join         copy_blocks as c       on          (c.parent_id, c.id) = (dc.parent_id, dc.id) 	0.000107318111949495
10591545	36149	how to find the last week's most sold books in sql	select top 10 b.bookid, count(b.bookid)  from tbsoldbooks b   group by b.bookid where saledate >= dateadd(day, -7, getdate())  order by 2 desc select top 10 b.bookid, count(b.bookid)  from tbsoldbooks b   group by b.bookid where saledate >= dateadd(month, -1, getdate())  order by 2 desc 	0
10595823	15725	mysql fetching data from multiple tables	select u.*,p.*,f.* from user u left join picture p on p.user_id = id inner join friends f on f.friends_of = u.id where f.friends_id = 1 	0.00314875200454632
10600875	27891	calculating the are of overlap between polygons in the same table	select      a.geog1.stintersection(b.geog2) as overlapgeog ,   a.geog1.stintersection(b.geog2).starea() as areaoverlap from (     select      geography::stgeomfromtext('point(0.0 0.0)',4326).stbuffer(100) as geog1 ) a inner join (     select      geography::stgeomfromtext('point(0.001 0.0)',4326).stbuffer(100) as geog2 ) b on a.geog1.stintersects(b.geog2) = 1 	0
10604427	11924	sql query - join two tables	select 'in temp1 but not temp2',temp1.* from temp1  outer join temp2 on temp1.a = temp2.a where temp2.a is null union select 'in temp2 but not temp1',temp2.* from temp2  outer join temp1 on temp2.a = temp1.a where temp1.a is null 	0.168821863414043
10621275	29614	mysql ordering and then grouping a query in mysql	select * from   mfw_navnode natural join (          select node_name, max(id) as id from mfw_navnode group by node_name        ) as dd where  node_name in ('eby', 'laa', 'mif', 'amaur', 'asn') 	0.202343428497223
10632528	7796	passing a table's just one value to another table in sql stored procedure	select @kullanicisehirid = sehirid from sehir where sehir.sehiradi=@kullanicisehir 	0.000292906646209429
10633415	21888	calculating top 5 users with the most points in the current category or category below it	select      `user_id`,      sum(if(`plus`, `points_amount`, 0)) - sum(if(`minus`, `points_amount`, 0)) as `points` from      `points_awarded` where     `user_id` = $user_id     and (         `category_id` = $cat_id         or `category_id` in(             select `links_to`             from `category_relations`             where `links_from` = $cat_id         )     ) group by `user_id` 	0
10650128	7543	is it posible to format a mysql decimal value output?	select replace(cast(100.00 as char), '.', ',') 	0.278506089485667
10662244	30800	sql query to find the common data	select idb from mytable where ida = 3 intersect select idb from mytable where ida = 4 	0.00176826138877475
10662607	13532	find out missing stored procedure	select p1.name, p2.name from db1.sys.procedures p1 full outer join db2.sys.procedures p2 on p1.name = p2.name where p1.name is null or p2.name is null 	0.198125977147388
10665869	31722	count result rows of table that is already counted and grouped by	select count(distinct name) from a 	0
10673241	22476	sql select friends change column name	select  memberid, friendid from    friends where   memberid = @memberid union all select  friendid, memberid from    friends where   friendid = @memberid 	0.00302344067783687
10673589	30789	sql aggregate unique pairs	select pg1.player_id as player1, pg2.player_id as player2, count(*) as num_games from (select distinct game_id, player_id       from  players_games pg      ) pg1 join      (select distinct game_id, player_id       from players_games pg      ) pg2      on pg1.game_id = pg2.game_id and         pg1.player_id < pg2.player_id group by pg1.player_id, pg2.player_id 	0.037372309389152
10674029	33545	sql/ php joining table, ignoring multiple records	select p.id, p.name, p.surname, group_concat(po.name) from players p  inner join player_position pp on pp.player_id = p.id inner join positions po on po.id = pp.position_id inner join sports s on s.id = po.sport_id where s.sport = 'football' group by p.id 	0.00397687285663538
10677242	12376	effective wayto sum values in mysql table rows	select product_id, sum(qty) from tablename group by product_id 	0.000706499580536631
10681736	27319	how to select users that match each other in matches table for a given id	select distinct m1.id_user_b from  matches m1 join matches m2 on m1.id_user_a = m2.id_user_b and m2.id_user_a = m1.id_user_b where m1.id_user_a = 4 	0
10682589	36023	oracle db - select multiple columns as alias	select prod_id as "product id", prod_name as "product name" from tbl_products 	0.131709344023875
10687392	201	mysql export value and not id	select a.id,a.time,a.quote,b.value as mediadesc,a.quantity, c.value as packdesc,a.username, a.email,a.company,a.contact_number,a.found_us‌​,a.additional_info  from wp_quotes a inner join wp_quote_forms_fields_values b on b.id = a.media inner join wp_quote_forms_fields_values c on c.id = a.pack 	0.00863138982254348
10713488	21383	sql: return unique users with specific preference settings	select distinct a.userid from   tusers a left join tprefvals b          on a.userid = b.userid where  b.prefid in ('20', '21') and b.`value` = 'es' 	0.00361670878493359
10722365	31305	limit results in sql	select p1.* from person p1 where p1.id in (     select top 5 p2.id from person p2     where p2.name = p1.name ) order by p1.id 	0.368874187300849
10736989	31971	how to find out number of days in month in mysql	select day(last_day(yourdate)) 	0
10743433	14332	selecting a column from a previous latest record	select apps.user_id, apps.date_of_application, apps.status,        ifnull(               (select app.score                from applications app               where  app.user_id = apps.user_id               and app.status = 'ended'                order by app.date_ended desc               limit 1), 10) as score from applications apps where  apps.status = 'active' order by apps.score asc,          apps.date_of_application asc 	0
10747355	41254	oracle 11g: unpivot multiple columns and include column name	select idnum, sk, f, e, h, 'f'||sk as col_name 	0.0156135026832653
10756050	28521	looping through two tables to generate a new table	select d.date, n.number from dbo.dates(@start, @finish) cross join      numbers n 	0.000277442367148762
10756467	23885	retrieve data using between some date range	select * from membership where '2011-01-31' between joineddate and leavedate 	5.36927805629352e-05
10761729	2088	mysql: create a view showing only a subset of a one-to-many relationship	select si.id, si.name, so.name, so.id  from singers si inner join songs so on so.singer_id = si.id where so.id = (select max(songs.id) from songs where songs.singer_id=si.id) 	0.00145750632671335
10779090	38708	forum mysql category, thread, post	select c.* , count(tp.num_thread) as num_threadcount , coalesce(sum(tp.num_postcount), 0) as num_postcount from forum_categories c  left join  (select count(p.num_post) as num_postcount,  t.num_thread, t.num_cparent, t.num_inactive from forum_threads t left outer join forum_posts p on p.num_tparent=t.num_thread and p.num_inactive=0 where t.num_inactive=0 group by t.num_thread) tp  on c.num_category=tp.num_cparent and tp.num_inactive=0 where c.num_inactive=0 group by c.num_category order by c.num_sticky desc, c.dte_created desc 	0.00850585554789078
10786487	867	msql join tables with same columns	select *  from (select * from table_2010       where date_created between '2010-04-01' and '2011-04-01'       union       select * from table_2011       where date_created between '2010-04-01' and '2011-04-01' ) as t order by date_created 	0.00913671015940953
10786973	21912	how to list parent category and sub-category data with proper order	select category from (   select      if(p.category_name is null, c.category_name, concat(p.category_name, ' > ', c.category_name)) as 'category'   from category c   left join category p on c.parent_category_id = p.category_id ) s order by category 	0.00549607390786755
10794472	39095	how to add where clause based on inner query	select     dpt.id  ,          dpt.name  ,          count(*) emp_count from       department dpt inner join employee e on         dpt.id = e.department_id group by   dpt.id  ,          dpt.name having     count(*) >= 10; 	0.1288183897655
10794843	22755	sql query for select data from multiple tables	select newtable.mydata, newtable.creationdate from (select mydata, creationdate from table1 union select mydata, creationdate from table2) as newtable order by newtable.creationdate desc 	0.00915480007236441
10797011	18557	sql lite data types - c#	select datetime(1092941466, 'unixepoch'); 	0.348708465080802
10805095	40928	sql query for "almost" duplicate entries (same values for last 3 columns)	select distinct * from   smtab natural join (   select   datetime, power1, power8   from     smtab   group by datetime, power1, power8   having   count(*) > 1 ) as t 	0
10819893	12870	sql query: calculating a matrix of totals	select       sum(`wte`) / 1000 as wte, o.band, o.age    from  `orthoptists` as o    left join `instances` as i    on o.instance_fk = i.id    where i.region = 14    group by o.band, o.age 	0.0605178506605212
10824545	21476	mysql display score 1 to 10	select distinct c.id, c.title, cv.title2 , (match ( c.title, c.title2, c.title3, c.title4 ) against('desktop') * 4.5 )  as score from job where match ( c.title, c.title2, c.title3, c.title4 ) against('desktop') order by score desc 	0.000195774941272942
10827852	36697	getting the above average student from database	select student_full_name      from (select student_full_name,                  avg(results) as average_sresult           from viewenrol           group by student_full_name) sre,           (select (avg(results)) tavg           from viewenrol) ta      where sre.average_sresult > ta.tavg 	0.000133925938159454
10835009	22729	verify existence of two columns in different tables in a single sql transaction	select     case when exists(select 1 from x where id = @id) then 1 else 0 end as isinx,     case when exists(select 1 from y where id = @id) then 1 else 0 end as isiny 	0
10838386	24525	return value from a third table field based on second table id	select t1.`id`          as `add id`,        t1.`name of add` as `add name`,        t3.`name`        as `type of add` from   `adds` as t1   left join `type of adds`   as t2 on t2.`add id`  = t1.`id`   left join `names of types` as t3 on t3.`type id` = t2.`id` 	0
10844436	4332	count, inner join	select driver_id, first_name, last_name count (participant.driver_id) as "number of accidents" from "participant in car accident" join driver on "participant in car accident".driver_id = driver.driver_id where responsibility='yes' group by driver_id, first_name, last_name order by count (participant.driver_id) desc 	0.746984244368854
10848065	30948	get records unique on both fields in a many-to-many relation	select  * from    (         select  *,                 count(*) over (partition by paymentid) as pcnt,                 count(*) over (partition by invoiceid) as icnt         from    mytable         ) q where   pcnt = 1         and icnt = 1 	4.92617150115157e-05
10866966	4578	sql joins with one to many relationship - combine the many into one row?	select pt.`id`,         group_concat(pr.`price` separator ',')    from `products` as pt     left join `prices` pr on pr.`product` = pt.`id`   group by pt.`id` 	5.42668931222545e-05
10871411	8189	rewrite to danish time / date	select id_forum, title, tekst, date_format(dato,'%d-%m-%y') as dato, id_brugere  from `forum`  order by  `forum` . `id_forum` desc limit 0 , 30 	0.541028849951914
10889235	37688	mysql limit 1 but query 15 rows?	select   ul.itemname from   userlist ul where   (ul.deleted = 0)  union  select   i.itemname from   (select     il.itemname   from     itemlist il    order by     il.ranking asc    ) as i limit 5  	0.0143601857496334
10901685	8225	separating data the right way	select things.*  from things  join type on thing.typeid = type.typeid  where type.name = 'one' 	0.419508694101566
10908559	20276	how to fetch data from multiple independent tables with no relationship	select un.common_id, coalesce(t1_value), coalesce(t2_value), coalesce(t3_value) from (select t1.common_id, t1.value as t1_value, null as t2_value, null as t3_value from t1 union  select t2.common_id, null, t2.value, null from t2 union  select t3.common_id, null, null, t3.value from t3) as un group by un.common_id 	0.000187195879894769
10912237	4793	sql select distinct rows and ignore row if blank	select distinct meta_value  from `wp_postmeta`  where meta_key = "aaa" and meta_value != ""; 	0.000834966130286632
10912747	37825	order by primary key	select column_name from information_schema.key_column_usage where objectproperty(object_id(constraint_name), 'isprimarykey') = 1 and table_name = 'person' 	0.0467987176300504
10921144	2396	how to find records that violate referential integrity	select * from table2 t2 where not exists(     select 1     from table1 t1     where t1.accountid = t2.accountid ) 	0.0056790914175586
10929997	7949	sum two rows in one - my sql	select  case test when 'not set' then 'no' else test end as newtest,         month, sum(testcount) from    mytable group by         newtest, month 	0.00270498962416836
10932726	9260	how to query 3 mysql tables and return matching results (with one to many relationships)?	select distinct tjobsoffered.fuserid , tusers.fname from tjobsoffered inner join  tjobsrequested on tjobsoffered.fuserid=tjobsrequested.fuserid left join tusers on tusers.fid=tjobsoffered.fuserid where   (tjobsrequested.fjobid (12,30) and (tjobsoffered.fjobid in (86 ,5) 	0.000254762991173752
10936496	7674	sql count and grouping	select      count(*) as 'total proposals',     sum(case when status = 'complete' or status = 'contract' then 1 else 0 end) as 'total contracts',     case userid          when '4' then 'at'         when '3' then 'eo'         when '11' then 'ct'         when '13' then 'mh'         else userid     end as salesman,     sum(case when status = 'complete' or status = 'contract' then contractamt else 0 end) as 'contract total',     avg(datediff(contractdate, proposaldate)) as averagedays,     sum(proposalamt) as ptot,     (sum(case when status = 'complete' or status = 'contract' then contractamt else 0 end) / sum(proposalamt)) as 'hit rate $s',     (sum(case when status = 'complete' or status = 'contract' then 1 else 0 end) / count(*)) as 'hit rate #s' from     (     select * from project     where (status != 'proposal' and status != 'lead') and userid = '13'     order by contractdate desc     limit 0, 30) a group by userid 	0.181060309944831
10940212	23510	mysql, max date form each relation	select     t.id_factor,     t.d_change,     t.date from (     select          mc.id_factor,          mc.d_change,          mc.date     from         money_change mc     inner join         money_factor mf using(id_factor)     where         mf.money_base = "dollar"     order by         mc.date desc ) t group by     t.id_factor 	0.000314191038611164
10948467	14167	how to join three or more tables in mysql	select  a.visitor_text,         a.company_text,         a.contact,         a.person_to_meet,         a.department_text,         a.floor,         b.belonging_type,         b.belonging_text,         a.intime,         c.exit_time  from    tm_visitor a           left join tm_belonging b on b.bid = a.id         left join tm_exit c on c.id = a.id 	0.222688993341638
10957784	18661	can i join to all rows in a reference table as a kind of template?	select    people.person_id, period_id = periods.id, is_scheduled = case   when schedule.person_id is not null then 1 else 0 end from dbo.[period reference table] as periods cross join  (   select person_id      from dbo.[person schedule table]      group by person_id ) as people left outer join    dbo.[person schedule table] as schedule   on people.person_id = schedule.person_id   and periods.id = schedule.period_id order by    people.person_id, p.id; 	0.00694973908412746
10975188	23886	selecting between more than 2 rows from db	select * from table where id between 20 and 30 or id between 40 and 50 	0
10980912	9111	how to fetch multiple results that reside in one column	select user_id, sum(views) from users where user_id = 67 group by user_id 	0.000676686246827984
10982870	12184	mysql : is there any way to reduce creation of so many views	select rad.state_id as state_id          ,  sum (case when oslc.candidate_id is not null then 1 else 0 end) as shortlisted          ,  sum (case when osec.candidate_id is not null then 1 else 0 end) as selected from registered_applicant_details rad      left outer join oc_shortlisted_candidates oslc            on (rad.applicant_id = oslc.candidate_id)       left outer join oc_selected_candidates osec             on (rad.applicant_id = osec.candidate_id)  group by rad.state_id; 	0.740140380030014
10990927	40045	how to check if record deleted was last record left mysql php	select count(*) from comments where post_id = (select post_id from comments where comment_id='$id') 	0
11012957	38067	mysql count frequency of records	select     a.class,     count(b.studentid) as 'no of students late',     sum(b.onetime) as '1 times',     sum(b.twotime) as '2 times',     sum(b.threetime) as '3 times',     sum(b.fourtime) as '4 times',     sum(b.fiveormore) as '5 & more' from     students a left join     (         select             aa.studentid,             if(count(*) = 1, 1, 0) as onetime,             if(count(*) = 2, 1, 0) as twotime,             if(count(*) = 3, 1, 0) as threetime,             if(count(*) = 4, 1, 0) as fourtime,             if(count(*) >= 5, 1, 0) as fiveormore         from              students aa         inner join             laterecords bb on aa.studentid = bb.studentid         group by              aa.studentid     ) b on a.studentid = b.studentid group by     a.class 	0.00107191870570859
11014181	13423	lost precision when selecting columns with calculations under android	select id, factory, cast( sum(round((cast(round((cast(price as real))*(cast((100-d1)/cast(100 as real) as real)),3) as real))* (cast((100-2)/cast(100 as real) as real)),3)* cast(units as real)) as varchar) from items  group by id, factory 	0.0911066734275258
11014243	37794	getting file name with out extension using sql query in sql server	select      substring([image], 0, charindex('.', [image], 0))  from      [table] 	0.260066842619535
11015516	730	specific date format	select convert(char(10), getdate(), 120); 	0.0112537294635861
11025567	6186	sql query not in, exist	select      a.stagename,     a.realname from     actor a left join     actedin b on a.stagename = b.stagename left join     movie c on b.title = c.title      and a.year = b.year      and c.earnings >= c.budget where      c.title is null group by     a.stagename,     a.realname 	0.741834294370337
11044251	38261	caclulate chinese year with mysql	select     (         case             when mod(a.year, 12) = 0 then 'monkey'             when mod(a.year, 12) = 1 then 'rooster'             when mod(a.year, 12) = 2 then 'dog'             when mod(a.year, 12) = 3 then 'pig'             when mod(a.year, 12) = 4 then 'rat'             when mod(a.year, 12) = 5 then 'ox'             when mod(a.year, 12) = 6 then 'tiger'             when mod(a.year, 12) = 7 then 'hare'             when mod(a.year, 12) = 8 then 'dragon'             when mod(a.year, 12) = 9 then 'snake'             when mod(a.year, 12) = 10 then 'horse'             when mod(a.year, 12) = 11 then 'sheep'         end     ) as zodiacyear from     table a 	0.0536292887289535
11045940	31042	how to find the biggest procedure in the database?	select o.type, o.name,      len(m.definition) - len(replace(m.definition, nchar(10), '')) as rows,     m.*  from sys.sql_modules m inner join sys.objects o on m.object_id = o.object_id order by 3 desc 	0.00164187308403669
11053266	21855	sql having a single column display value from different tables	select t1.submissionstatus  from table1 t1 join table0 t0 on t1.primarykey = t0.foreignkey union select t2.submissionstatus  from table1 t2 join table0 t0 on t2.primarykey = t0.foreignkey union select t3.submissionstatus  from table1 t3 join table0 t0 on t3.primarykey = t0.foreignkey 	0
11075803	12777	efficient way to store chronological rows?	select * from grades where timestamp > 123 order by timestamp asc limit 200; 	0.0558454945655263
11083900	27420	getting sub data from a list of facilities	select id, name, city, state, selcount from t  where exists (   select 1 from   (select name, city, state, max(selcount) selcount      from t      group by name, city, state) s   where s.name = t.name and s.city = t.city and s.state = t.state and s.selcount = t.selcount ) 	0.00139408204244123
11101210	30978	combine two tables with a left join in mysql	select * from table1 s left join table2 as t on s.name=t.name where t.name is null 	0.11083369897082
11114787	19584	sql server multiple date languages in same query	select     months,     shortmonths,     days from     master.dbo.syslanguages where     alias in ('english','french', 'german') 	0.0368329099710348
11119737	31709	get records in order of conditions in where in clause	select * from foo where id in(2,3,4,1,5) order by find_in_set(id, '2,3,4,1,5'); 	0.0123349567480573
11120447	28169	sql - how to get data from two tables	select table_a.*, articles.* from table_a join articles on articles.user_id = table_a.user_id  where table_a.user_id = 1 order by table_a.created_at asc; 	0.000101950018101391
11130585	11166	want select to return multiple values in a single row	select name, group_concat(start_time order by start_time) as start_times from your_table group by name order by count(start_time) 	9.32639360692889e-05
11139072	23317	sql: creating unique id for item with several ids	select pid, epid,   min(t1.epid,       coalesce(t2.epid, t1.epid),       coalesce(t3.epid, t1.epid),       coalesce(t4.epid, t1.epid),       coalesce(t5.epid, t1.epid)) npid from table t1 join table t2 on t1.epid = t2.pid and t2.epid not in (t1.epid) join table t3 on t2.epid = t3.pid and t3.epid not in (t1.epid, t2.epid) join table t4 on t3.epid = t4.pid and t4.epid not in (t1.epid, t2.epid, t3.epid) join table t5 on t4.epid = t5.pid and t5.epid not in (t1.epid, t2.epid, t3.epid, t4.epid) group by pid, epid 	0
11140647	14276	mysql - concat two fields and use them in where clause	select concat_ws(' ', first_name, last_name) as name from `users` where concat_ws(' ', first_name, last_name) like "%john doe%" 	0.208267983196687
11147312	21601	sql select and sum from three	select a.id, a.name, isnull(sum(b.amount), 0) as bsum, isnull(sum(c2.amount), 0) as csum from a  left outer join b on a.id = b.ida left outer join (select c.idb, sum(c.amount) as amount from c group by c.idb) as c2 on c2.idb = b.id group by a.id, a.name 	0.0148478253216613
11156155	30472	how to write a query which fetches data from a table without the quotes and double quotes in the data stored	select empid,          replace(replace(empname,'"', ''),'''','') empname,            replace(replace(compname,'"', ''),'''','') compname  from table 	0.00612233300867823
11166936	24718	ssis groupby / master - detail file export	select a.id, (select top 1 b.name from tablea b where a.id = b.id) from tablea a group by id 	0.0464832940422783
11175901	37536	how to select data from multiple tables using joins/subquery properly? (php-mysql)	select   projectdetails.projectdetailsid,   projectheader.projectid,   projectheader.projectname,   projectheader.lead,   projectheader.startdate,   projectheader.enddate,   projectheader.status,   projectheader.remarks,   projectdetails.employeeid,   employee.firstname,   employee.lastname,   concat(lead.firstname,' ',lead.lastname) as leadname from   projectheader,   projectdetails,   employee,   employee as lead where projectheader.projectid = projectdetails.projectid and projectdetails.employeeid = employee.employeeid and projectheader.lead = lead.employeeid 	0.0376462864711051
11176716	20277	how to use order by in sql server on a column of a table?	select * from   yourtable order  by str1,           str2 	0.0101186377318641
11203669	29657	max on two columns in mysql	select max(t2.c1) as c1,         max(t1.c2) as c2  from   t t1         inner join (select max(c1) as c1                     from   t) t2                 on t1.c1 = t2.c1 	0.00208121814155023
11205905	22684	reference postgresql query column in other column	select *, num+1 as field2 from (    select row_number() over (...) as num, ... as field1 from ... ) t 	0.00852202531741367
11209888	34381	sql select query to pull multiple values from the same row as individual rows	select 'cty_cd' as type,  cty_cd as code from tablename where cty_cd = 'den'  union  select 'state_cd' as type, state_cd as code from tablename where cty_cd = 'den'  union  select 'country_cd' as type, country_cd as code from tablename where cty_cd = 'den' 	0
11210887	18257	mysql group, join and select max	select m.*, u.*, u2.* from (`messages` as m) left join users as u on u.user_id=m.message_from left join users as u2 on u2.user_id=m.message_to where (m.`message_from` != 1 and m.`message_to` != 1) and m.`message_id` in (     select max(`message_id`)      from `messages`      group by `message_conversation_id`      having `message_id` = m.`message_id`) order by m.message_id desc; 	0.2724334903674
11217641	26541	mysql join on self based in similar fields	select     a.id as report_id,     max(case when b.field_name like 'service_id_%' then b.field_value end) as field_id,     max(case when b.field_name like 'service_name_%' then b.field_value end) as name,     max(case when b.field_name like 'service_cost_%' then b.field_value end) as cost from     reports a inner join     custom_report_fields b on a.id = b.report_id where     a.id in (100, 101) and     b.field_name like 'service_%' group by     a.id,     substring_index(b.field_name, '_', -1) 	0.0386337551194799
11221223	40454	distinct mysql query combine	select distinct t.`to_name_f_kana` from       (      select m.*, c.name as corp_name       from mail_log as m, corp as c        where             m.send_date >= '$term_from'                   and            m.send_date <= '$term_end'      ) t group by t.send_date; 	0.115446520920158
11222023	24949	finding the list of people who have birthday this week	select  dateadd(week, datediff(day, 0, getdate())/7, 0) firstdayofcurrentweek,          dateadd(year, datediff(year, dogumtarihi, getdate()), [dogumtarihi]) birthdaythisyear,         dateadd(week, 1, dateadd(week, datediff(day, 0, getdate())/7, 0)) firstdayofnextweek                      ,[adi]           ,[soyadi]           ,[dogumtarihi]           ,[birimadi]           ,[mudurlukadi]           ,[gorevi]           ,[ceptelefonu]           ,[evtelefonu]          from    personel where   dateadd(year, datediff(year, [dogumtarihi], getdate()), [dogumtarihi]) >= dateadd(week, datediff(day, 0, getdate())/7, 0)         and         dateadd(year, datediff(year, [dogumtarihi], getdate()), [dogumtarihi]) < dateadd(week, 1, dateadd(week, datediff(day, 0, getdate())/7, 0)) 	0
11225491	8765	select one row from multiple row in sql depands on condition	select   intemployeeeid,  dteattendancedate as 'attendance date'  min(dteattendancetime) as 'attendance in'  max(dteattendancetime) as 'attendance out' from  tblemployeeattendance group by  intemployeeeid,  dteattendancedate 	0
11233753	14042	while loop in sql for top 10	select clientusername, desthost, count(desthost) counts  from  #proxylog_record        where clientusername  in (select top 10 clientusername from #proxylog_count_2)       group by clientusername, desthost order by counts desc 	0.0237834421255355
11237855	3112	query statement with multiple conditions?	select * from articles where (content like 'keyword1' or content like 'keyword2' or content like 'keyword3') and (date between '2012-06-18 00:00:00' and '2012-06-25 23:59:59') order by date asc 	0.753532343274236
11239193	40457	select 1 row from table where foreign key table records exist	select p.* from products as p inner join productimages as pi on p.id = pi.product_id group by p.id 	0
11249982	15242	incomprehensible query result looking for rows in a query which are not in other query	select distinct iddireccionine from direccionine as di   where iddireccionine not in (select distinct direccioncorregida.iddireccionine                              from direccioncorregida                              where direccioncorregida.iddireccionine is not null) 	0.012245688748851
11251503	692	selecting counts with conditions and grouping	select count(distinct processid) from table where eventcode < 0 	0.0238968864097701
11270313	28497	select by latest date	select uid, date_made, bid from   ${wpdb->prefix}auction_bids natural join (   select   uid, max(date_made) as date_made   from     ${wpdb->prefix}auction_bids   where    pid = $pid   group by uid ) as t where  pid = $pid 	0.00168516970293925
11283272	38786	query for joining 2 tables and create a new column based on the output	select case when amount_value > 5000 then 1             else null        end stamp_value   from t1 join t2 ... 	0
11284671	22998	query to aggregate amount across different rate categories as applicable per usage	select sum(t) as yes from ( select pc.client_id, pr.hourly_rate, round((( sum(tt.time_end) - sum(tt.time_start))/3600),2) as difference, (round((( sum(tt.time_end) - sum(tt.time_start))/3600),2) * hourly_rate) as t from track_time as tt, project_track as pt, project as pr, project_clients as pc, clients as cl where tt.track_id = pt.track_id and pt.project_id = pr.project_id and pr.project_id = pc.project_id and pc.client_id = cl.client_id and cl.client_id = " . $db->prep($client_id) . " group by hourly_rate) as table1 	0.00027520356352822
11289681	33157	search full name in database with php when first and lastname are in different fields	select        concat_ws(' ', firstname,lastname) as name from         table where         name like '%$keywords%' 	0.00466136576357858
11301290	18870	how can i get a list with sublists using one query?	select i.*, group_concat(si.name) as subitems from items i left join subitems si on si.item_id = i.id group by i.id 	0.00395513499287452
11315034	15449	if i add 360 months to begin_date, how can i accurately obtain end_date using a lookup fact table?	select b.*  from so_total_days2 a inner join so_total_days2 b on b.monthnumber = a.monthnumber + 360 where a.from_date =  '2010-01-01' from_date   to_date     days_in_month monthnumber 1980-01-01  1980-01-31  31    1 1980-02-01  1980-02-29  29    2 1980-03-03  1980-03-31  31    3 ... 1981-01-01  1981-01-31  31    13 1981-12-01  1981-12-31  31    24 ... 1985-01-01  1985-01-31  31    49 1985-12-01  1985-12-31  31    60 	0.00123232270241628
11316408	17563	sql select how to insert column name and provide value	select name, address, 'no' as vacationing, zipcode from mytable; 	0.00469618254708751
11324433	751	foreign key fails to create	select * from registratiebehandelingen a where userid is null or not exists (select 1 from users b where b.userid= a.userid) 	0.0137974011442835
11325268	37017	how do i use group by based on a case statement in oracle?	select (case     when exp_date > sysdate then 1     when exp_date <= sysdate then 2     else 3  end) expired, count(*) from mytable group by (case     when exp_date > sysdate then 1     when exp_date <= sysdate then 2     else 3  end) 	0.484276346375937
11330603	12900	oracle sql: identify open cases for each week during a year	select a.esu_per_gro_id,            a.esu_id,            a.status,            b.mov_id,            b.mov_start_date,            b.mov_end_date,            a.esu_start_date,            a.esu_end_date,            ls.cls_desc,            'week' || trim(to_char(pd.prd_period_num)) week_desc   from a   left join b     on b.mov_per_gro_id = a.esu_per_gro_id       left join ls     on ls.cls_code = a.status       left join o_periods pd     on b.mov_start_date < pd.prd_end_date and        (b.mov_end_date is null or         b.mov_end_date > pd.prd_start_date) and        a.esu_start_date  < pd.prd_end_date and        (a.esu_end_date is null or         a.esu_end_date > pd.prd_start_date) where b.mov_start_date is not null and       a.status <> ('x') and       pd.prd_cal_id = 'e1190' and       pd.prd_year = 2012 order by week_desc 	0
11334674	5546	how do i select rows where a column value starts with a certain string?	select * from mytable where name like "mr.%" 	0
11338598	28742	how to make crosstab query in mysql	select     projectid,     sum(case when level = 0 then programmingtime else 0 end) as level0,     sum(case when level = 1 then programmingtime else 0 end) as level1,     sum(case when level = 2 then programmingtime else 0 end) as level2,     sum(case when level = 3 then programmingtime else 0 end) as level3,     sum(case when level = 4 then programmingtime else 0 end) as level4 from     tbl group by     projectid 	0.757487701587908
11345685	37167	performance issue using new paging stynax in sql server 2012 (offset n rows fetch next m rows only)	select p.productname from products p order by p.productid    offset 10 rows    fetch next 10 rows only 	0.0119149881004953
11349108	7735	find identical values from mysql table from two columns	select * from  auto a, ( select x, y, count(*) from auto group by x, y having count(*) > 1 ) b where a.x = b.x and a.y = b.y 	0
11365689	27804	select in then oracle	select ra1.rate, ra1.effective_date from rates_all ra1 where ra1.effective_date = add_months(&&eff_date, -5)    or (ra1.effective_date = add_months(&&eff_date, -5)-1    and not exists(select * from rates_all ra2                   where ra2.effective_date = add_months(&&eff_date, -5)) 	0.149018222865145
11369238	39220	mysql searching for nearest less than numerical value	select a.jday,        (select max(layer) from table2 where elevation<=a.tl1) as tl1,        (select max(layer) from table2 where elevation<=a.tl2) as tl2,        (select max(layer) from table2 where elevation<=a.tl3) as tl3,        ... from table1 as a 	0.013849070684256
11370447	34744	sql filtering id's	select count(`hotelid`) as `freq`, `hotelid`          from `reservation`      group by `hotelid`      order by `freq` desc limit 5 ; 	0.0213511504702077
11379874	27064	sqlite: select date and time from (text) date field in phonegap/cordova	select date(date) as date, time(date) as time from ...... 	0.000212482479029213
11381125	18007	mysql group by, having, order by query	select     c.*, b.* from     (         select recipe_id, max(added) as mostrecent         from recipe_versions         group by recipe_id     ) a inner join     recipe_versions b on          a.recipe_id = b.recipe_id and         a.mostrecent = b.added inner join     recipes c on a.recipe_id = c.id order by     c.added 	0.662371492812967
11381195	2248	subtracting a value in a column by average of the same column without using a variable in isql	select     sname,     marks - (select avg(marks) from marks as m2 where m2.studentnum = m.studentnum) from     marks as m inner join     student as s         on s.snum = m.studentnum 	0
11384649	20650	how to get the sentence number for each words in words table in sql?	select table.id, table.word, count(*) + 1 as serial_number from table left join ( select id, word from table where word like '%.' ) z  on table.id > z.id group by table.id, table.word 	0
11392195	32154	get max and min from fields	select f.id, f.title  min(least(s.one, s.two, s.three, s.four)) as min,  max(greatest(s.one, s.two, s.three, s.four)) as max  from first f  inner join second s on f.id = s.first_id  group by f.id, f.title 	0.000504683113099915
11392335	24638	is it possible to use a single query to achieve related purchase history?	select        distinct productid  from        [orderhistory] oh  where       oh.orderid in (select orderid from orderhistory where productid = 4 ) 	0.775692987298706
11403101	19620	group by manager id	select * from emptbl ;with cteemp(emp_id,emp_user_id,emp_name,emp_mgr_id) as ( select emp_id,emp_user_id,emp_name,emp_mgr_id from emptbl where emp_user_id='d070' union all select  et.emp_id,et.emp_user_id,et.emp_name,et.emp_mgr_id from emptbl et inner join cteemp e on et.emp_mgr_id = e.emp_id) ,cteemp1(emp_id,emp_user_id,emp_name,emp_mgr_id)as (select emp_id,emp_user_id,emp_name,emp_mgr_id from cteemp where emp_user_id<>'d070') select * from cteemp1 	0.0270698675600272
11405446	36093	find top 10 latest record for each buyer_id for yesterday's date	select first 10 *     from testingtable1    where buyer_id = 34512201 order by created_time desc; 	0
11415906	12642	child table result concatenation	select  emailqueue.id, emailqueue.senderaddress, emailqueue.recipientlist,         emailqueue.cclist, emailqueue.subject, emailqueue.body, emailqueue.bodyhtml,         emailqueue.disclaimerfooter, emailqueue.sent, emailqueue.senderror,          emailqueue.createddate,         substring((select ( ', ' + eqa.attachmentpath)                            from emailqueueattachments eqa                            where emailqueue.id = eqa.emailqueueid                            for xml path( '' )                           ), 3, 1000 ) as [path list] from emailqueue  where         (emailqueue.sent = 0) and (emailqueue.senderror = 0) and (emailqueue.bodyhtml is null) 	0.017189234827528
11420703	13615	how to add group by values in a column in a mysql table	select   ip,   page,   concat(min(date), " - ", max(date)) as date_range,   sum(page_views) as total_page_views from stats_tracker group by page order by total_page_views desc 	0.000422527453437402
11423360	35256	sql join with max	select  b.appname , a.username,  a.msgnumber, max(to_char(a.entrydate)) from serverlogdetail a, serverlogid b where a.msgnumber = 1020055  and a.entrydate between (sysdate-90) and sysdate and a.something = b.something            group by b.appname, a.username, a.msgnumber order by b.appname, max(to_char(a.entrydate)) 	0.544154886588289
11425129	30336	join with null values not returning values	select *  from   allrecordsview k         join dbo.split(@keyword, ',') t           on ( coalesce(k.description, '')                + coalesce(k.name, '') + coalesce(k.items, '')                + coalesce(k.products, '') ) like '%' + t.items + '%'  where  k.username = @username 	0.204096171011906
11428583	1431	which of the or statement was selected?	select *,         case when shape.col1 = 'square' and colour.col1 = 'blue'             then 'blue'              when shape.col1 = 'square' and colour.col2 = 'pink'             then 'pink'              ...        end as selected_color from colour where ... 	0.0410612668834496
11429819	27954	mysql query with group by and order	select sum(points) as total, country  from table  where season >= x  group by country  order by total desc, (select t2.points from table t2 where table.country=t2.country order by t2.season limit 1) desc 	0.646137110191322
11430173	16826	how to select data and execute function just once for each grouped selected value	select      tt1.org as 'organization',      tt1.ponumber as 'po number',     tt1.code as 'code',     tt1.price as 'price', sum(round(tt1.priceprice,2,1) as 'sumprice'     from my_table as tt1 group by tt1.ponumber 	0
11437221	36232	add a computed column in sql query	select     vm.prefvacationid,    description,    case when vmap.prefvacationid is not null then 'true'    else 'false'    end isselected from vacationmaster vm left outer join vacationmapping vmap on vm.prefvacationid = vmap.prefvacationid  and vmap.userid = @userid 	0.0198141818577837
11438919	24706	selecting records where all columns have data and are not null	select * from table1 where (val1 and val2 and val3 and val4) is not null 	0
11444990	6582	grouping mysql results by multiple columns and time span	select nid, max(timestamp), uid, weeks_ago from (select nid, timestamp, uid, floor(datediff(now(), from_unixtime(timestamp))/7) weeks_ago       from mytable) x group by nid, uid, weeks_ago 	0.00247667005519952
11452100	8404	sql multiple join and count	select      *,     avg(rate.score),     (select              count(report.comment_id)         from             report         where             comment.id = report.comment_id) as num_reports from     comment         left join     rate on (comment.id = rate.comment_id) group by comment.id 	0.330449657970079
11453006	7621	avoid repetative column data using select query in oracle	select        case         when f.fyeardescr = lag(f.fyeardescr) over (order by f.fyeardescr)         then null         else f.fyeardescr       end                          as fyeardescr   , p.paymnthid   , p.paymnthnm   from financialyear f, mnthpll p  where f.status = 'a' and p.fyearcd = f.fyearcd 	0.420734730316889
11460267	3348	filter query with result of aggregate	select a.*, b.maxrevisiondate as latest_revision from proposal_proposal a left join (     select proposal_id, max(created) as maxrevisiondate     from proposal_proposalrevision     group by proposal_id ) b on a.id = b.proposal_id left join proposal_opinion c on     a.id = c.proposal_id and     (b.maxrevisiondate is null or c.created > b.maxrevisiondate) and     c.user_id = <user_id here> where c.proposal_id is null 	0.445330033122796
11461587	10162	collecting data from 3 tables into 1 query	select t.id, t.title, count(m.user_id) members, (     select count(1)     from users u3      inner join team_members m3 on u3.id = m3.user_id      and m3.team_id = t.id and u3.score > (         select score from users where name = 'johan'     ) ) + 1 score from teams t inner join team_members m on t.id = m.team_id where t.id in (     select team_id      from team_members m2     inner join users u2 on m2.user_id = u2.id     where u2.name = 'johan' ) group by t.id, t.title 	0.000567016653092296
11474020	27281	selecting between a range of dates, controlling for age at those dates	select tl.*,  from trans_logs tl where customer_age + (sysdate- trans_date)/365 = 20 	0
11478033	18275	oracle group by, take first element from non-grouped column	select person_id, account_login, add_date   from (select table.*              , dense_rank() over (partition by person_id order by add_date) rnk          from table)  where rnk = 1; 	0.000348203143188064
11482057	4741	how to find a column group by another column in a given date using mysql	select visiter_ip as visiter_ip,         sum(page_views) as page_views  from <table_name>  where visiter_ip = '214.21.45.1'    and date = curdate(); 	0
11500143	9344	sqlite union and sort order	select * from ( select 'none' as col1, '0' as col2 union  select  * from category where id='2'  ) t order by case when col1='none' then 0 else 1 end 	0.312058932499549
11510298	13132	select using group by and having not returning records	select     a.firstname,     a.lastname,     a.phone,     a.email,     a.title,     a.lmu from tm_user a inner join (     select lastname     from tm_user     group by lastname     having count(1) > 1 ) b on a.lastname = b.lastname 	0.192029468793162
11510738	39097	sql: outputting multiple rows when joining from same table	select * from table where id = 1 union select * from table where oldid = 1 	0.000211103907391429
11518354	11586	sql server rank() by group	select #t.*, salesrank from #t inner join  (      select employee, product, rank() over (partition by employee order by sq desc) as salesrank      from      (select employee, product , sum (quantity) sq from #t group by employee, product) v ) v      on #t.product = v.product     and #t.employee =v.employee 	0.491486501477784
11536618	12661	mysql count + grouping for a field value	select   `date`,   sum(if(`code`=0,1,0)) as `code0`,   sum(if(`code`=1,1,0)) as `code1`,   sum(if(`code`=2,1,0)) as `code2`,   sum(if(`code`=3,1,0)) as `code3`,   sum(if(`code`=4,1,0)) as `code4` from   tablename group by `date` 	0.00405247553060593
11539036	38231	sorting table based on a condition	select fname||' '||lname as emp_name,salary,hire_date from employee  e join department d on e.dept_id=d.dept_id  order by (case when d.name='sales' then hire_date end),            (case when d.name<>'sales' then salary end) desc 	0.00223984029195852
11541286	1362	selecting numbers "larger" than a given number	select id    from table_name   where id >= (select max(id)                  from table_name                 where id <= 12) 	0
11545437	64	in mysql, how to "join" three tables	select     teams.name,     sum(payfiles.deals_passed) as team_deals_passed from payfiles left join persons using (hash) left join teams using (team_id) group by teams.team_id 	0.109580137014871
11545778	12780	compound select query in oracle database	select count(1)    from mealdb   where timeofday='afternoon' and userid='1200'; 	0.593135787305809
11546935	41210	sql: calculate the change in values over an n-day period	select         t1.home_pitcher,         t1.date,         t1.all_starts_whip,        (select t2.all_starts_whip from mlb_data t2          where          t2.date < date_sub(t1.date, interval 1 month)          and t2.home_pitcher=t1.home_pitcher          order   by t2.date desc limit 1) as previous_whip,         t1.all_starts_whip - previous_whip      from          mlb_data t1 	0.00115714508420793
11550651	32132	exploding array of struct using hiveql	select  * from (select user_id, prod_and_ts.product_id as product_id, regex_replace(prod_and_ts.timestamps, "#\\d*", "")  as timestamps from table2 lateral view explode(purchased_item) exploded_table as prod_and_ts) prod_and_ts; 	0.105980342377831
11567894	21536	how to join 2 columns in a sql table to one column in another sql table?	select a.coursename,c.coursename from coursetable as a left outer join prereqtable as b on a.courseid=b.courseid left outer join coursetable as c on b.prereqcourseid=c.courseid 	0
11580996	24156	c# comparing date ranges	select        row_number() over (order by billid, startdate),       case when (billprice>pricingprice) then 'credit' else 'debit' end,       billid,       datediff(d, startdate,enddate)+1 as days,       billprice-pricingprice  from  (       select             billid,             case when effectivefrom>billedfrom then effectivefrom else billedfrom end startdate,             case when isnull(effectiveto,getdate())<billto                  then isnull(effectiveto,getdate()) else billto-1 end enddate,            bill.price as billprice,            pricing.price as pricingprice       from pricing      inner join bill                 on bill.accountid= pricing.accountid                  and (billedfrom<isnull(effectiveto,getdate())) and (billto>effectivefrom)                 and bill.price <> pricing.price   ) v 	0.00511938103491197
11588259	13350	how do you display comment count if there is no comment posted it will display in a formview?	select     bm.messageid,     count(bc.commentid) as comment_count,     bm.addeddate,     bm.author,     bm.title from blog_message bm left join blog_comments bc on bm.messageid = bc.messageid  group by bm.messageid 	0.000215770728420049
11598237	24007	how to print a sum of column in all rows in sql	select      a.player_name,      a.number_of_goals,      (a.number_of_goals / b.goalsum)*100 as percent_scored,     b.goalsum from        myplayerinfo a cross join      (select sum(number_of_goals) as goalsum from myplayerinfo) b 	0
11599565	40529	reading xml in table	select * from ( select     t.item.value('../../../requestreference[1]', 'varchar(20)')  as requestreference,     t.item.value('../../@inventoryid', 'varchar(3)')  as inventoryid,     t.item.value('../../@inventoryname', 'varchar(3)')    as inventoryname,     t.item.value('.', 'varchar(5)')   as code from       @xmldoc.nodes('    as t(item) )t order by inventoryid, inventoryname, code 	0.0394077093500093
11601640	37809	naming the bins of histogram	select cast(interval*50 as nvarchar(max)) + '-' + cast(interval*50+49 as nvarchar(max)) 	0.114683471559589
11604800	35111	mysql matching columns from same table	select a.page, c.userlikes, c.friendlikes from m_likes a inner join app_pages b on a.page = b.id cross join (     select         count(case when user = '1' then 1 end) as userlikes,         count(case when user = '2' then 1 end) as friendlikes     from m_likes     where user in ('1','2') ) c where a.user in ('1','2') group by a.page having count(1) = 2 	0
11605735	20172	how to join tables in mysql	select m.id, m.message, s.username, r.username from users_messages m  inner join users s on m.sender_id = s.id inner join users r on m.receiver_id = s.id 	0.173106101236595
11609811	31025	repeating results inner join query	select f.friend_id,f.status,f.uid, b.owner_id,b.price, b.currency,b.item_name,b.item_id,bs.productid,bs.userid,bs.photo_thumb,u.uid,u.fname,u.lname,u.profile_pic  from users_profile u inner join friend_list f on u.uid=f.friend_id inner join bs_items b on b.owner_id=f.friend_id inner join bs_photos bs on b.item_id=bs.productid  where f.status=1 and f.uid='5'  group by f.uid order by b.timestamp desc 	0.76774862343928
11613751	33465	mysql calculate medium value of a count(*) with a group by somefield	select avg(num_login)    from (select count(*) as num_login    from logins group by user_id) as num_logins 	0.00140764739962694
11626599	19079	ms-access group by, top query	select min(tablea.id) as id, tablea.type, tablea.date,  sum(tablea.val) as total, tableb.sumb  from tablea left join tableb on tableb.id = tablea.id  group by tablea.type, tablea.date, tableb.sumb ; 	0.485281117529179
11627368	27327	using between in the middle of where clause based on an if condition	select * from mytable  where myfield = 1 and (@docalculatevalues = 0 or myimportantfield between @fromvalue and @tovalue) 	0.00388751690196015
11629845	38198	how to write select statement based on score column result using sql server?	select s.*, case when score is null                  then '                  when score > 70                  then 'pass'                  else 'fail'             end as result from students s 	0.00689301145396642
11632809	34545	pl/sql copy/insert multiple rows to one row in another table	select ipf_ipuc, 'gp',        max(case when ipf_code = 'ipq_ref1tit' then ipf_valu end),        max(case when ipf_code = 'ipq_ref1org' then ipf_valu end),        max(case when ipf_code = 'ipq_ref1al1' then ipf_valu end)  from srs_ipf, srs_cap  where ipf_ippc = cap_mcrc and ipf_ipuc = cap_stuc    and ipf_code in ('ipq_ref1tit', 'ipq_ref1org', 'ipq_ref1al1')  group by ipf_ipuc 	0
11634107	26599	trouble with a sql using between and multiple occurences	select name, category from users where `in` <= 2010 and (         `out` > 2010 or name in (             select name             from users             where `in` = 2011             )         ) 	0.168665407508733
11645543	32019	force primary key on a view	select  row_number() over (order by dbo.stockcardsstores.idstore_cardstore desc) as id_pk, isnull(dbo.stockcardsstores.idstore_cardstore, newid()) as idstore_cardstore ,         nullif(dbo.stockcard.idstockcardindex, newid()) as idstockcardindex ,         dbo.stores.storename ,         dbo.stockcardsstores.idpurchaseinvoice ,         nullif(dbo.stockcard.designation,'') from    dbo.stores         inner join dbo.stockcardsstores on dbo.stores.idstore = dbo.stockcardsstores.idstore         right outer join dbo.stockcard on dbo.stockcardsstores.idstockcardindex = dbo.stockcard.idstockcardindex 	0.0621735612729842
11647278	18923	sql query to retreive the matched field from a keyword using or operator	select *, case when zip = 'ny'                 then 'zip'                when name = 'ny'                 then 'name'                when city = 'ny'                 then 'city'           end as found from zip_codes where 'ny' in (name, zip, city) limit 1 	0.0922488159026845
11649154	16002	how to convert a float column into a datetime	select startdate + stuff(right('0' + rtrim(starttime), 4), 3, 0, ':')    from dbo.table   where isdate(startdate) = 1 and convert(int, starttime) < 2400   and convert(int, starttime) % 100 between 0 and 59; 	0.00112994561205785
11652536	1144	mysql returning correct link depending on the least value	select     title,             my_value,             my_ink,             least(site_a_value, site_b_value, site_c_value) as lowest_value,                  case least(site_a_value, site_b_value, site_c_value)             when site_a_value then site_a_link             when site_b_value then site_b_link             when site_c_value then site_c_link end as lowest_value_link, from stock 	0.000663884949012906
11656476	20032	mysql, order by insertion order, no sorting columns	select * from mytable ; 	0.0836475902786212
11665720	41231	sql server ordering based on two columns - parent and child	select primary, secondary from (select t.primary, t.secondary,              max(case when tsub.primary is not null then 1 else 0 end) as hasprimary       from t left outer join            t tsub            on t.secondary = t.primary       group by t.primary, t.secondary      ) a order by (case when hasprimary = 1 then secondary else primary end),          hasprimary desc,          secondary 	0
11666295	8956	replace value in result by a specific value	select      field1 as 'name',     case          when field2 = 'foo'              then 'bar'          when field2 = 'lorem'             then 'ipsum'         else 'some value'     end     as 'type',     field3 as 'description' from table 	0.00110023048813206
11668210	8862	php mysql get the nearest-latest record if a record is not exist (datetime based)	select *  from table  where field <= '2012-06-25'  order by field desc  limit 1 	0
11673944	14362	sql server 2008 : character encoding	select serverproperty('collation') 	0.755180935320755
11680025	11195	how to generate random number without repeat in database using php?	select floor(rand() * 99999) as random_num from numbers_mst  where "random_num" not in (select my_number from numbers_mst) limit 1 	0.000464005740141217
11682581	21539	get xml data in to table	select t1.n.value('@name', 'varchar(max)') as portal,        t2.n.value('.', 'varchar(max)') as [indes] from @t as t   cross apply xmlcol.nodes('/queue/portal') as t1(n)   cross apply t1.n.nodes('indexesforselect/index') as t2(n) 	0.00309885728239256
11686498	39325	how to find the current time slot matches with any of the table field?	select  (((datepart(hour,getdate())-6)*2)-1)+          case when datepart(mi,getdate())>30 then 1                else 0 end [timeslot_number] 	0
11720153	782	mysql increase field by count of regexp matches	select *,     param1 regexp "reg1" +     param2 regexp "reg2" +     param1 regexp "reg3" as match_count from 	0.0131987033470605
11722329	30791	how to search informix database for a column	select tabname, colno, colname   from systables a, syscolumns b  where a.tabid = b.tabid  and colname = "cust_nbr" order by colno; 	0.202189926670161
11723262	30127	sql query - get rows only if value falls within range of "last n records" (record-specific)	select * from countries left join (         select weather.country_id          from weather              inner join              (select country_id, max(daynum) as maxdaynum from weather group by country_id) maxday                 on weather.country_id = maxday.country_id                 and weather.daynum>maxday.maxdaynum-3                 where rain=1         ) rainy on countries.id = rainy.country_id where country_id is null 	0
11725811	25123	mysql get number of summed rows	select sum(score) as sum_score from players where  clan !=0 and clan !=  ".$our_clan."   group by clan having sum_score  > " .$our_clan_score . " 	0
11744816	37433	select columns in same row as max(column)	select id,`status`,user,location from     (      select a.id, 'checked-out' `status`,co.`time`, co.user, co.location      from assets a left join asset_checkouts co on a.id=co.asset      union all      select a.id, 'checked-in' `status`, ci.`time`, ci.user, ci.location      from assets a left join asset_checkins ci on a.id=ci.asset      where not ci.`time` is null     ) u where `time` = greatest((select coalesce(max(`time`),0)                          from asset_checkouts co                          where co.asset=u.id),                         (select coalesce(max(`time`),0)                           from asset_checkins ci                          where ci.asset=u.id)) 	0.000139514504867003
11745103	13734	compare two tables and find matches in ms-access 2007	select * from firsttrial inner join consolidateddatabase  on firsttrial.modelnumbr = consolidateddatabase.modelnumbr; 	0.00386802449255312
11745575	15080	show data from 2 tables which have same column name	select e.empname,d.deptcode,d.deptname  from employee e inner join dept d   on e.deptcode = d.deptcode; 	0
11752907	38266	oracle 10g : sql merging rows into single rows	select co.course,ma.count as  'math',sc.count as 'science',co.count as 'computer',ch.count as 'chemistry' from  (select course,[count],row_number() over(order by  [count]) as row_num from t_course where subject = 'math')ma full outer join  (select course,[count],row_number() over(order by  [count]) as row_num from t_course where subject = 'science')sc on sc.row_num=ma.row_num full outer join  (select course,[count],row_number() over(order by  [count]) as row_num from t_course where subject = 'computer')co on co.row_num=sc.row_num full outer join  (select course,[count],row_number() over(order by  [count]) as row_num from t_course where subject = 'chemistry')ch on co.row_num=ch.row_num 	0.000207251810261568
11753388	30682	mysql select in with sub-query	select * from messages where (receiver = 123510 and sender = 123457 and status <> 3) or       (receiver = 123457 and sender = 123510 and status <> 4); 	0.666228949201103
11754192	5255	like operator to retrieve the results	select * from street where street_name like replace('%park ave 10%',' ', '%') 	0.228244471518785
11756406	33767	get current date in java	select * from orders where status='q' and date = curdate(); 	0.000835370323516133
11763364	34412	sql: finding differences between rows	select name, count(*) / 2 as difference_5 from (   select a.name name, abs(a.value - b.value)    from  tbl a join tbl b using(name)   where abs(a.value - b.value) between 1 and 5 ) as t group by name 	0.000333566695623157
11789007	24853	getting data using 4 tables	select t."topic_name", t."rank", t."user_name" from      (select tt."name" as topic_name, tu."actual_rank" as rank, tu."name" as user_name,         row_number() over (partition by tt."name" order by tu."actual_rank" desc) user_rank     from "trendingtopics_trendingtopic" tt     left join "trendingtopics_trendingtopiccycle" ttc on ttc."tt_id" = tt."id"     left join "trendingtopics_tweet" tw on tw."tt_cycle_id" = ttc."id"     left join "trendingtopics_twitteruser" tu on tu."id" = tw."user_id") t where t."user_rank" = 1 	0.0259463392844955
11792899	25543	sql select within a range of seconds	select * from run where run_datetime < datedadd(s, '14:25:29.563', 30) and       run_datetime > datedadd(s, '14:25:29.563', -30) 	0.000936686695369968
11795565	40567	how to get the customer detail + whether he has (an) order or not	select c.*      , case when o.customerid is not null             then 1              else 0          end hasorders      , o.numberoforders from customers c left join (      select customerid           , count(*) numberoforders        from orders       group by customerid ) o on c.customerid = o.customersid 	0
11839370	27782	how to get date in multiple tables in mysql database?	select name from course c,skillset s where c.cid= s.cid. 	0.000738977723677127
11839641	27244	get duplicate data of same field from table with compare other field of same table	select  partid from    mytable group by partid having  count(partid) > 1 	0
11842710	39774	mysql change sum value	select *, case when op_code = 9                then @s := units                else (@s := @s + (units * add_or_subtract))            end as sum from your_table, (select @s := 0) st 	0.0239650221683066
11846563	24548	get auto increment in query as a variable to use in another query	select itemid_sequence.nextval from dual 	0.00105466577038767
11859391	34542	get an array in a field after a join	select a.idappointment,group_concat(cast(ca.idclient as char) separator ',')  from appointments a inner join clientsappointments ca on ca.idappointment = a.idappointment group by a.idappointment 	0.00521421376551904
11862661	24380	sql group by on a sub query	select products.* from products      inner join  (     select productid, sum(quantity) as quantitysum     from     (         select productid, quantity           from basketitems           union all           select productid, quantity           from orderitems      ) v     group by productid ) producttotals     on products.id = producttotals.productid order by quantitysum desc 	0.615655062762819
11874328	14908	listing all rows that have a duplicate entry in a particular column in mysql table	select * from users where name in(select name from users group by name having count(1) > 1) 	0
11880199	23627	how do i count unique items in field in access query?	select count(*) as n from (select distinct name from table1) as t; 	0.00279437594728443
11891763	30524	join two tables using or operator	select upc,ean,productname from maintable m1 left join maintable2 m2 on m2.upc = m1.upc union select upc,ean,productname from maintable m11 left join maintable m22 on m22.ean = m11.ean 	0.744290405750703
11893785	24500	sql mathematical calculations based on text column	select     ((case when col1 = 'stable' then 1.0 else 0.0 end) +     (case when col2 = 'stable' then 1.0 else 0.0 end) +     (case when col3 = 'stable' then 1.0 else 0.0 end)) / 3.0 from yourtable 	0.0130924273223303
11900477	37408	selecting non-repeating values in postgresql	select distinct on (a.s_id)            a.s_id, select2result.s_id, select2result."mnrphone",            select2result."dnrphone"    ... 	0.013100759033207
11928360	27058	output mysql list of records, grouped by category?	select category, group_concat(prodname) as product from recipes group by category order by category, prodname asc 	4.92619463145257e-05
11929019	38253	android - sqlite date query	select column from table where columndate between '2012-07-01' and '2012-07-07' 	0.412269838390887
11930816	34482	find any of days is fall under list of dates	select   * from   yourtable where       to_date   >= @from_date_parameter   and from_date <= @to_date_parameter 	0
11932915	38206	map label date with database date	select * from user_master where replace(convert(varchar,visit_date,106),' ','-')='"+label1.text+"'; 	0.0113378926629346
11933141	35839	result set from two tables looping multiple times	select      *  from      assignment_status s,      question_bank b,      assignment_answers a where      s.test_group_id = b.group_id = a.g_id = 'q1' and b.q_id = a_q.id 	0.000105966558386761
11964148	14859	sql to select brand from a table, if another table has a product with that brand	select p.brand from products p, stock s  where p.productid=s.productid and s.storeid='1' 	0
11966618	11419	sql inner join on 2 conditions where possible	select * from       #table2 c       inner join mapping f                     on c.id1 = f.id1 and                    c.id2 = isnull(f.id2, c.id2) 	0.763907696638041
11968801	2167	mysql syntax - selecting selecting rows based on multiple arguments?	select b.title, b.rating from books b left join book_genres bg on(bg.book_id = b.book_id) where b.book_id = 2 	0.000757826556541404
11973671	33607	how to check if a count statement returns a specific value	select rev.name, s.title, count(r.mid) from reviewer rev, song s, rating r  where (r.rid = rev.rid) and (r.mid = s.sid)  group by rev.name, s.title having count(r.mid) = 3 	0.00174279822222863
11978504	30974	mysql join usage	select * from tablaa, tablab where tablaa.name = tablab.name 	0.779593358370359
12006789	10727	select only records with last timestamp of its kind	select l.iduser, l.lat, l.lng, l.timestamp from ( select iduser, max(timestamp) as maxtimestamp from locations group by idusuario) as max inner join locations as l on l.idusuario = max.idusuario and l.timestamp = max.maxtimestamp group by idusuario 	0
12013191	37946	what is the most efficient way to calculate installed base?	select     p.unitid,     p.country,     p.yearcolumn,     p.environment,     p.placement,     sum(ibp.placement * frr.rate) installedbase from     @placements p     inner join @placements ibp on         p.unitid = ibp.unitid         and p.country = ibp.country         and p.environment = ibp.environment         and p.yearcolumn >= ibp.yearcolumn     inner join @curveassignments rr on         ibp.unitid = rr.unitid         and ibp.country = rr.country         and ibp.environment = rr.environment         and ibp.yearcolumn = rr.yearcolumn     inner join @curvedefinitions frr on         rr.rateid = frr.rateid         and p.yearcolumn - ibp.yearcolumn = frr.yearoffset group by     p.unitid,     p.yearcolumn,     p.country,     p.environment,     p.placement 	0.158454666764991
12029608	17115	select query in sql	select field-1, field-2,.....,field-n from tablename where (field-1 between value-1 and value-2) and (field-2 between value-3 and value-4) and (field-3 in ('value-5', 'value-6',...,'value-n')) ............ and (field-n ....[condition].......) where [condition] 	0.44368253527461
12029914	6379	querying the same value from the same table with two joins or two ons	select o.order_id as oid, customer_id as cid,     empp.username as packer,    empt.username as taker from orders o left join employees empp on emp.user_id = o.packedby left join employees empt on emp.user_id = o.takenby where o.customer_id =3 	0
12040875	40846	query to return aggregate based on two unique dimensions?	select    c.desiredcolumns,    p.category,    p.item    p.totalprice from    dbo.customers c    inner join (       select          h.customerid,          v.category,          v.item,          sum(l.price) totalprice       from          dbo.order_header h          inner join dbo.order_lines l             on h.orderid = l.orderid          cross apply (             values                ('type', [type]),                ('mfr', manufacturer)          ) v (category, item)       group by          h.customerid          v.category,          v.item    ) p on c.customerid = p.customerid 	0.000370288493519943
12051064	3219	mysql subqueries	select short_date, sum(time_spent_in_sessions), sum(nb_of_sessions)  from (both your queries here) as subquerytable 	0.730224068315294
12052815	30136	query forumaltion with multiple joins and multiple count for each table	select box_code.id,         count(distinct box_code_unused.id ) as total,         count(distinct box_code_used.id ) as total2,         count(distinct box_code_expired.id ) as total3 from box_code left join box_code_used on box_code_used.box_code_id = box_code.id left join box_code_unused on box_code_unused.box_code_id = box_code.id left join box_code_expired on box_code_expired .box_code_id = box_code.id group by box_code.id 	0.00359850540285946
12072820	37225	select distinct years and their months in a single query	select x.`year`, group_concat(x.`month`) as months from     (         select distinct year(sc_ts) as `year`, monthname(sc_ts) as `month`         from             `posts`         where             user_id = 1         order by             month(sc_ts)     ) x group by     x.`year` order by     x.`year` 	0
12083794	34074	make 2 select statements from 2 tables and then join the result with third table	select ab.*, c.* from ((select *        from a       ) union all       (select *        from b       )      ) ab right join      c      on ab.cat_id = c.id order by date 	0.000134142922035593
12095450	39407	how to put a multivalued attribute in one column in a query?	select bk.book_title, group_concat(bt.book_id separator ', ') from book_tags bt join books bk on bk.id = bt.book_id join tags t on t.id = bt.tags_id group by bt.book_id 	0.00019185253099317
12110239	29091	count column values with range specified - sql	select sum(case when [time] > 6 and [time] <= 12 then 1 end) [more than 6 hours],        sum(case when [time] > 12 and [time] <= 24 then 1 end) [more than 12 hours],        sum(case when [time] > 24 then 1 end) [more than 24 hours] from (  { your-query-here } ) a 	0.00136039632826248
12117019	23561	how to give priority over one like statement in sql	select * from products where productname = ? limit 10 union select * from products where productname like ? limit 10 union select * from products where productname like ? limit 10 	0.277120209370846
12133130	4228	while($row = mysqli_fetch_array($result)){ when selection multiple tables	select *, kunde.id as kundeid from kunde inner join vip on (vip.brugerid = kunde.id) where  kunde.id=1 and email like '%$keyword%' or fornavn like '%$keyword%' 	0.183994750399552
12138869	15206	db query: how to count maximum for several columns	select max(nbr_of_adults) max_adults,        max(nbr_of_children) max_children from (   select        sum(case when person_type = 'adult' then 1 else 0 end) as "nbr_of_adults",       sum(case when person_type = 'child' then 1 else 0 end) as "nbr_of_children"     from my_table   group by claim_date ) a 	0.000436410760743055
12157282	28826	oracle sql query to get manager to employee relation	select * from employees where sysdate between start_date and end_date and sup_id = 'sup1'; 	0.0154856815510993
12161362	25132	how to ignore a tsql where condition when the value of a filter is null in one statement?	select * from mytable where     (@filter1lowerbound is null or column1 > @filter1lowerbound) 	0.0069968419242005
12180692	21600	another sql statement i don't understand	select      top 5      n.news_id,      n.is_spotlight,      n.location_id,      n.news_title,      cast(n.news_content as varchar(200)) as news_content,      n.writing_date,     n.publication_date,      n.end_date,      n.alt_uri,      n.youtube_code,      n.icon_img_file,      n.banner_img_file from      (select          1 as rank,         n.news_id     from rcde_news n     where n.location_id = 4     and n.is_spotlight = 1 and n.publication_date < getdate() and n.end_date > getdate()     and n.status_id = 2     union     select          2 as rank,         n.news_id     from rcde_newstolocation ntl     inner join rcde_news n on ntl.news_id = n.news_id     where ntl.location_id = 4     and n.status_id = 2     ) as news inner join rcde_news n on news.news_id = n.news_id where n.is_spotlight = 1 and n.publication_date < getdate() and n.end_date > getdate() order by rank desc, publication_date desc 	0.247722426827584
12185209	22514	how to purposely return a null from tsql query	select null 	0.0266426894859992
12186380	13246	join 3 tables in sql	select t1.*, t2.* from t1, t2, t3 where t1.id=t2.id and t2.id=t3.id 	0.22359786391073
12186742	29605	conditional table change in mysql query	select    a.id,            coalesce(b.id, c.id) as ans_id,           coalesce(b.answer_text, c.answer_text) as answer_text from      ref a left join ref_ans b on a.id = b.q_id left join us_states c on a.type = 'st' where     a.id = <id> and (               (a.type <> 'st' and b.id is not null) or               (a.type =  'st' and c.id is not null)           ) 	0.507249709646139
12187914	4150	sql server difference between a blank column and column with value = 'null'	select isnull(col1,'')+ ' ' + cast(isnull(col2,'') as varchar(10)) as concat_col 	0.000504976499897904
12195558	19530	greatest value of multiple columns with column name?	select @var_max_val:= greatest(col1, col2, col3, ...) as max_value,        case @var_max_val when col1 then 'col1'                          when col2 then 'col2'                          ...        end as max_value_column_name from table_name where ... 	6.97071799405169e-05
12202181	2219	using user defined function (udf) in where clause more than once with running the function only once	select id, task_name, last_run, func.next_run from tasks cross apply (select dbo.task_next_run(task_type, @task_schedule_day_of_week, @task_schedule_time, @task_period, @last_run) as next_run) as func where  func.next_run < getdate() and func.next_run > last_run 	0.295772123446429
12212171	34465	sql query depending upon current time	select * from @data where value != 'first value' and (value != 'second value' or not ( '2012-08-29 23:59:59' between '2012-08-30 23:59:59' and '2012-09-15 23:59:59')) 	0.000355621556261826
12213379	19825	how to read from database which stocks have been bought but not yet sold?	select t1.sp100_id, t1._date as buy_date, t1.price from (select * from portfolio where action='buy')  t1     left join (select * from portfolio where action='sell') t2        on t1.sp100_id=t2.sp100_id     and t1._date<t2._date where t2.sp100_id is null 	0.000806294367413081
12218173	26176	get top comments out of database	select   id,   text,   (rating/timeofrating) as score from tablename order by score desc limit 10 	0.000268994971189537
12219972	5430	how to collate rows to a delimited string in sql2008r2	select distinct a.formnumber, maincategories from yourtable a cross apply (select stuff((select ',' + value                             from yourtable                            where formnumber = a.formnumber for xml path('')),1,1,'') maincategories) b 	0.0511175819931174
12227354	27639	sql for last changed value before given index	select resource_id,         date_id,         value  from   resources,         (select resource_id,                 max(date_id) as date_id          from   resources          where  date_id <= 6          group  by resource_id ) temp  where  resources.resource_id = temp.resource_id         and temp.date_id = resources.date_id 	5.48733339644746e-05
12237020	6256	mysql avoid duplicate urls	select id from table where url = @url 	0.143127042910838
12252910	28278	mysql max query then join?	select      *  from      operators     join products         on operators.idoperators = products.idoperator      join      (         select              idproducts,              max(date)          from results          group by idproducts      ) as t     on products.idproducts = t.idproducts order by drawndate  desc limit 20 	0.294512602273281
12259367	8967	how do i get the latest group in mysql?	select gid,max(grp)as 'higest_grp' from example group by gid 	0.000537243874540682
12265300	23905	retrieve first email from string in sql row	select     ltrim(rtrim(cdu_mail)),          substring(ltrim(rtrim(cdu_mail)), 0, charindex(';',ltrim(rtrim(cdu_mail + ';'))))  from #clientes 	0
12282688	29889	how to link 4 tables using an mysql query	select * from vehicle v inner join info   i on          v.id = i.vehicle_id inner join axle1 a1 on i.vehicle_id  = a1.vehicle_id inner join axle2 a2 on a1.vehicle_id = a2.vehicle_id 	0.102162183711649
12283007	37262	mysql select query, post tags	select post_id, group_concat(tag_name) as tag_name from post  left join post_tag  on post_tag.id_post = post.post_id left join tags on post_tag.id_tag = tags.tag_id     group by post_id order by post_id  desc limit 5 	0.0173891529544261
12297062	23632	pick distinct rows based on two tables t-sql	select * from table1 left join table2 on table1.referenceid = table2.referenceid where table2.referenceid is null 	0
12300529	21998	method in mysql to accept dates in custom formats	select str_to_date( '04/31/2004', '%m/%d/%y' ) ; 	0.671485963874808
12302554	16739	how to retrieve the date records based on today's date in c# and mysql	select * from my_table where date(datetimefield) = current_date 	0
12303017	27201	summary information column in mysql query	select a.*, b.totalcount from     (         select sds.district_id,detail.year, detail.race, sum(count)         from    school_data_race_ethnicity_raw as detail                     inner join school_data_schools as sds                          using (school_id)         group by district_id, year, race     )   a inner join     (         select sds.district_id,detail.year, sum(count) totalcount         from    school_data_race_ethnicity_raw as detail                     inner join school_data_schools as sds                          using (school_id)         group by district_id, year     )   b on a.district_id = b.district_id and             a.year = b.year 	0.0552442395292083
12304099	34084	select query ignore field	select  `provider`, count(distinct name) from    tablename where   name not in             (                 select name                 from tablename                 where operation = 'p'             ) group by provider 	0.109504176922003
12306801	19603	how to select rows from 2 tables where 1 column from each can be merged via common purpose?	select a_created as x_created,a_data,null as b_data  from table_a union all  select b_created as x_created,null as a_data,b_data  from table_b order by 1 	0
12319255	40087	change one column's value during a select - sql	select id, name, '10' as class, school from students 	0.000113132026579391
12325132	21269	mysql get missing ids from table	select a.id+1 as start, min(b.id) - 1 as end     from testtable as a, testtable as b     where a.id < b.id     group by a.id     having start < min(b.id) 	7.51809089782071e-05
12330235	2840	first and last records from group by. cannot get last	select `date`, value1 as start,  (select value2 from photos where t.date >= adddate(`date`, interval 1-dayofweek(`date`) day) and  t.date <= adddate(`date`, interval 7-dayofweek(`date`) day) order by date desc limit 1) as enddate from table t  group by year(`date`), week(`date`,7) 	0
12330682	30821	merge two query when using hibernate	select a.name from activity as a where a.parent.id =      (select p.category.id from project as p where p.id =:projectid) 	0.466087740617587
12330990	22331	sql conditional relations	select * from product p join apple a on (p.producttype = 1 and p.productid = a.id) join orange o on (p.producttype = 2 and p.productid = o.id) 	0.79340207599492
12331423	30337	mysql count and if usage	select itemid, count(*),  case when uid = 1001 then true else false end as toggled  from unlikes  where itemid in ('9999', '8888') group by itemid; 	0.33543810901843
12349768	18453	how to retrieve the sql server sid in string format?	select master.dbo.fn_varbintohexstr(sid)  as 'sid'  from sys.server_principals where name='##ms_sqlauthenticatorcertificate##' 	0.00331657302665315
12372419	5696	retrieving list of referenced tables from a sql view using a query	select * from sys.dm_sql_referenced_entities(n'dbo.exampleview', n'object'); 	0.000204591056424687
12372579	32156	select rows from second table based on id from first	select * from products as p inner join stock as s on p.id = s.id where fk_group_id = 11 	0
12373851	35436	removing duplicates and combining data from one table in a sql query	select       a.channel as channel_id,       a.start as start,       a.stop as stop,       a.value as signal,       b.value as noise from       table2 as a       join table2 as b       on            a.channel = b.channel and            a.start = b.start and            a.stop = b.stop and           a.type = 'signal' and           b.type = 'noise' 	0.000501734148757854
12377816	31138	using a select statement as one of the columns	select index_imsid, sum(weighted_value) sumweightedvalue,     (select top 1 percentof from [v_planperprovider1] where [plan_rank]=1) percentof     (select top 1 [plan_name_or_payment_type] from [v_planperprovider1] where [plan_rank]=1) plan_name_or_payment_type   from [v_planperprovider1]   where plan_rank between 1 and 10   group by index_imsid   order by 1 	0.00144485517638281
12381948	19358	select max count per second	select count(id), indatetime from news group by indatetime 	0.000218167198844052
12386091	23508	sql: insert space before numbers in string	select left(col,patindex('%[0-9]%',col)-1 )+space(1)+        case          when patindex('%[.]%',col)<>0             then substring(col,patindex('%[0-9]%',col),len(col)+1-patindex('%[.]%',col))                 +space(1)+                 substring(col,patindex('%[.]%',col)+1,len(col)+1-patindex('%[.]%',col))          else substring(col,patindex('%[0-9]%',col),len(col)+1-patindex('%[0-9]%',col))        end        from tab 	0.0246854443495755
12391687	30026	modify existing information about tied or equal values	select c5.eventgender, c5.distance, c5.style, c1.place, c3.givenname,  c3.familyname, c6.countryname, c4.givenname, c4.familyname, c7.countryname from results c1     inner join results c2 on c1.place = c2.place and c1.eventid = c2.eventid          and c1.competitornum < c2.competitornum     inner join competitors c3 on c3.competitornum = c1.competitornum     inner join competitors c4 on c4.competitornum = c2.competitornum     inner join events c5 on c5.eventid = c1.eventid     inner join countries c6 on c6.countrycode = c3.countrycode     inner join countries c7 on c7.countrycode = c4.countrycode order by c1.eventid; 	0.129426204244293
12391846	27453	logic with mysql query multiple tables	select a.apiname, a.description, a.endpoint from apis a inner join subscriptions b on b.api_id = a.apiname where b.user_id = '1234' 	0.629659844637293
12395834	28037	sql - get a count from a single table based on certain column criteria	select substr(uuid,1,42), count(user)   from ply  group by substr(uuid,1,42) having count(*) > 5 	0
12402032	34761	how to make sort case insensitive while displaying the lower+upper case of values in the dropdown	select product_id, product_name from (     select distinct (p.product_id) as product_id ,(p.product_name) as product_name,       lcase(p.product_name) as pname     from unified.techlibrary tl, unified.techlibraryprod pl, unified.product p, unified.contenttype ct      where tl.id = pl.id      and pl.product_id = p.product_id      and tl.contenttype_id in (1,3)       and pl.product_id not in (0) ) as x order by x.pname 	0.478012025745105
12404189	2799	mysql - selecting first and last row of data from 1 table from a certain user	select   t.userid,          first.value1 as value1_old,          first.value2 as value2_old,           last.value1 as value1_new,           last.value2 as value2_new from     (   select   userid, min(date) as first, max(date) as last   from     score   where    userid = 1        and date between '2012-09-02 00:00:00' and '2012-09-04 00:00:00' ) t     join score first on first.userid = t.userid and first.date = t.first     join score  last on  last.userid = t.userid and  last.date = t.last 	0
12409373	23025	sql - monthly average rather than daily average	select    location,           avg(value),           month(date)           year(date) from      value group by  location,           month(date),           year(date) 	0
12411633	15137	access 2007: query that counts from several tables	select u.userfullname, nz(rd.rawcount,0) as rawcount, nz(rp.rptcount,0) as rptcount  from (tbluser as u      left join (select username, count(reportnum) as rawcount from tblrawdata group by username) as rd      on u.userabbrev = rd.username)      left join (select userid, count(reportnumber) as rptcount from txtreports group by userid) as rp      on u.userid = rp.userid where (not p.payments is null) or (not n.notes is null); 	0.0432874503349924
12413951	10889	sql totaling by day	select thedate, new_users,        sum(new_users) over (order by thedate) as cumulative_new_users from (select trunc(create_dtime) as thedate, count(player_id) as new_users       from player       where trunc(create_dtime) >= to_date('2011-apr-22','yyyy-mon-dd')       group by trunc(create_dtime)      ) t order by 1 	0.0134110849399628
12415832	13594	sql query to return results if user entered "abcd-efgh" instead of "abcdefgh"	select * from dbo.mytable where   dbo.editdistance(mycol,@searchstring)<2 	0.00468354808159304
12418296	9469	create a temporary table in sql on the fly	select * into #temptable from mytable where 1=0 	0.00443137454341932
12423568	8917	combining sum statements to one table	select  varday,          count(*) as vol,         sum(fops_rehab) as fops_rehab,         sum(fops_recovery) as fops_recovery,         sum(case when fops_recovery = 1 then current_balance_amount else 0 end) rec_bal,         sum(case when fops_rehab = 0 then current_balance_amount else 0 end) reh_bal where   processing_date > '31/aug/2012' and rownumber =1  group   by varday order   by varday 	0.00901926033258991
12429120	38122	return (one valued and others empty) row in one - to - many relationships	select (case when seqnum = 1 then x end) as x,        (case when seqnum = 1 then y end) as y,        value from (select xy.*, x.value,              row_number() over (partition by xy.x order by xy.value) as seqnum       from x join            xy            on x.x = xy.x order by x, y 	0.000259601197640287
12430906	29606	sql convert sample points into durations	select groupid, pid, min(time), max(time) from (select t.*,              (dense_rank() over (order by time) -               row_number() over (partition by pid order by time)              ) as groupid       from t      ) t group by groupid, pid 	0.100844092669869
12435279	11216	join on timestamp range	select   raw_commits.sha,   raw_commits.author   raw_commits.date,   milestones.name from   raw_commits left outer join   milestones on   raw_commits.date between milestones.start and milestones.end 	0.00851439841995523
12438070	30036	sql result in a different order	select * from (  select *   from  `tattoos`   order by id asc  limit 176 ,5 ) as t order by id desc 	0.0413927843539384
12445269	19741	combine multiple query with one standart column	select   ta.id as id_valuenume   ,ta.name   ,tb.value from tablea ta left join tableb tb on ta.id=tb.valuenum union select   tb.valuenum   ,ta.name   ,tb.value from tableb tb left join tablea ta on ta.id=tb.valuenum 	0.00848438836683947
12445705	32528	how to get the result for the same user?	select t1.*  from thetable t1  join thetable t2  on t1.emp_num = t2.emp_num         and t1.doc_num = t2.doc_num      and t1.serial <> t2.serial    	7.1453078534258e-05
12449708	24486	left join twice form same table	select ... ,        g1.address as g1_address, g1.latitude as g1_latitude,         g1.longitude as g1_longitude, g1.method as g1_method,         ... ,        g2.address as g2_address, g2.latitude as g2_latitude,         g2.longitude as g2_longitude, g2.method as g2_method,         ... 	0.0621657388667031
12455192	40430	average no of games per player in last week	select count (distinct gameid)/count(distinct userid) from   your_table where  dateid>dateadd(dd,-7,'7-sep-2012') 	0
12466000	26221	query database, rearrange, insert into new table	select username, score, (select count(h.username)+1 from users u, (select username, score from users) h where u.username = 'userg' and (h.score > u.score)) as 'rating' from users where username = 'userg'; 	0.0159529428097249
12468245	18944	how can i specify the order of results within groups when querying derby?	select o.date_created, o.buyer_name,        (select max(date_created) from orders where buyer_name = o.buyer_name) as most_recent_date from orders o order by most_recent_date, o.buyer_name, o.date_created desc 	0.0333440343015511
12476384	33237	how to remove outliers from an activerecord query in rails	select stddev(amount) from answers 	0.778066427855925
12477102	27562	mysql join puzzle: inner and left join at the same time	select * from courses inner join xrefschoolsteachers     on courses.schoolid = xrefschoolsteachers.schoolid left join xrefcoursesteachers     on (xrefcoursesteachers.teacherid = xrefschoolsteachers.teacherid and xrefcoursesteachers.courseid = courses.id) where          xrefcoursesteachers.teacherid is null     and         cousers.id = ? 	0.58159281992541
12490325	41247	convert ms-access last() function to sql server 2008	select top 1 number from (   select number from title order by number desc ) 	0.377323134820752
12499846	35471	sql - create a column to group rows and count sequentially	select col1,        col2,        dense_rank () over (partition by col1                          order by col2) group_column   from test_table;       col1 co group_column        100 aa            1        100 aa            1        100 aa            1        100 bb            2        100 bb            2        100 cc            3        100 dd            4        100 dd            4 	0.00337471950879834
12501204	24284	listing top 5 users measured by most common rows in foreign key table	select t.teacher_id, t.name as teacher_name, count(*) as total from observations o left join teachers t on o.teacher_id = t.teacher_id left join criteria c on o.id = c.observation_id where c.criteria_id = 5 group by t.teacher_id, t.name order by total desc limit 5 	0
12518294	24736	sql server query to pull a combination values from the table	select * from t  where      clientid in      (         select t1.clientid          from              t t1 join t t2              on t1.clientid = t2.clientid          where              (t1.status = 'processed' and t2.status = 'inprogress') or              (t2.status = 'processed' and t1.status = 'inprogress')     ) 	0.000238069078321034
12520257	27703	group ohlc-stockmarket data into multiple timeframes - mysql	select min(a.mydate),max(a.myhigh) as high,min(a.mylow) as low,  min(case when rn_asc = 1 then a.myopen end) as open, min(case when rn_desc = 1 then b.myclose end) as close from(  select  @i := if((@lastdate) != (floor(unix_timestamp(mydate)/300 )), 1, @i + 1) as rn_asc,           mydate, myhigh, mylow, myopen, myclose,           @lastdate := (floor(unix_timestamp(mydate)/300 )) from   onemindata_1,   (select @i := 0) vt1,   (select @lastdate := null) vt2 order by mydate ) a inner join( select  @j := if((@lastdate1) != (floor(unix_timestamp(mydate)/300 )), 1, @j + 1) as rn_desc,           mydate,myclose,           @lastdate1 := (floor(unix_timestamp(mydate)/300 )) from   onemindata_1,   (select @j := 0) vt1,   (select @lastdate1 := null) vt2 order by mydate desc )b on a.mydate=b.mydate group by (floor(unix_timestamp(a.mydate)/300 )) 	0.0261586990324501
12525707	5450	i want date like 21-sep-12 in sql	select replace(convert(varchar(9), getdate(), 6), ' ', '-') as [dd-mon-yy] 	0.436518314275362
12567410	6969	i need best practice in t-sql export data to csv (with header)	select 'object_id', 'name' union all select object_id, name from sys.tables 	0.174404753364484
12610823	14200	sql query to get multiple max values from multiple columns	select top 5 date, val  from (select date, a as val from t       union all       select date, b from t       union all       select date, c from t ) as x order by x.val desc 	0
12616653	28114	deriving and saving the historical values into a separate table, or calculate the historical values from the existing data only when they're needed?	select staffid, sum(vacation) from (     select staffid, sum(vacationallocated) as vacation      from allocations     where allocationdate<=convert(datetime,'2010-12-31' ,120)     group by staffid     union     select staffid, -count(distinct holidaydate)      from holidaytaken     where holidaydate<=convert(datetime,'2010-12-31' ,120)     group by staffid ) totals group by staffid 	0
12629036	24699	why does distinct show different results when using group by in mysql	select distinct id, sex  from user  where sex=0  order by id limit 10 	0.547687824297962
12629312	30441	locate & count all duplicates of subset of columns in table with query	select count(*) as number, orgid, identifiertypeid, identifierorder, validfrom     from xdb.dbo.organizationidentifier_ingestii     group by orgid, identifiertypeid, identifierorder, validfrom     having count(*) > 1; 	0.000113614440877259
12630340	6772	mysql: generate a summary column without collapsing any rows	select t.uniqueid, t.word, q.minid as wordhash     from yourtable t         inner join (select word, min(uniqueid) as minid                         from yourtable                         group by word) q             on t.word = q.word 	0.0019326119966381
12633243	22434	trying to group by date for datetime type but not time with mysql	select date(`day`) as `day`, count(*) totalcount from   table  where  date between date() and tardate  group by date(`day`) order by day desc 	0.0584330363040277
12636220	2904	how to get an product limit in a category using php mysql?	select id, name, category_id from   products p where  (    select count(*)     from   products f    where  f.category_id = p.category_id and           f.id <= p.id ) <= 2; 	0.00221522752420625
12643289	12147	pass result of a query into stored procedure	select *  from tablea cross apply dbo.youruserfunction(column1, column2, etc) 	0.208965923865093
12651758	35351	how to merge empty field with the following value in mysql?	select max(row1), max(row2), max(row3) from tablename 	0.00144785698421391
12652037	31145	how to find if a list/set is contained within another list	select order_id from orders where product_id in (222,555)  group by order_id having count(distinct product_id) = 2 	0.000443383441169741
12670846	10039	mysql duplicate results joining tables	select a.*,p.price from (       select d.product, d.product_id        from cscart_product_descriptions as d        where d.product_id in (          select product_id from cscart_products where product_code in (          select product_id from cscart_range where range_name in (          select range_name from cscart_range where product_id = '0140885'          )))a join cscart_product_prices as p on p.product_id=a.product_id 	0.0106819419406185
12673365	31576	group data in monthly report using start date and end date	select officername, jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec from (     select left(datename(month,tourstartdate),3) mon, officername     from tbl     union all     select left(datename(month,tourenddate),3) mon, officername     from tbl     where month(tourstartdate) != month(tourenddate) ) p pivot (count(mon) for mon in (jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)) pv 	0.000290182459889102
12680126	36404	advanced sql query on wordpress filter by category and custom field	select distinct wpostmeta1.meta_value    from $wpdb->posts wposts      left join $wpdb->postmeta wpostmeta1 on wposts.id = wpostmeta1.post_id       left join $wpdb->postmeta wpostmeta2 on wposts.id = wpostmeta2.post_id       left join $wpdb->term_relationships on (wposts.id = $wpdb->term_relationships.object_id)      left join $wpdb->term_taxonomy on ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)    where wpostmeta1.meta_key = 'portata'      and wpostmeta2.meta_key = 'other-custom-field-value'      and $wpdb->term_taxonomy.taxonomy = 'category'      and $wpdb->term_taxonomy.term_id in($variabile_c)    order by wpostmeta1.meta_value asc 	0.194401004646433
12683248	3469	sql: select multiple columns based on multiple groups of minimum values?	select * from ( select a.id, b.id, a.time_point, b.time_point,  rank() over (partition by a.id, b.id order by calculatedvalue() asc) ranker from orientation_momentum a, orientation_momentum b where a.id = '00820001001' and b.id between 10 and 20 ) z where ranker = 1 	0
12686112	23666	merge two retrived rows by variable	select  stuff((select ', ' + cast(entry_template_id as varchar(50))        from entries t2 where t1.entry_template_name = t2.entry_template_name         for xml path('')), 1, 2, '') ids,  max(entry_template_name) entry_template_name,  max(book_display_name) book_display_name,  sum(entry_count) entry_count, sum(value_count) value_count,  sum(null_value_count) null_value_count,  avg(null_percentage) null_percentage,  sum(followed_value_count) followed_value_count,  sum(followed_null_value_count) followed_null_value_count,  avg(followed_null_percentage) followed_null_percentage from entries t1 group by entry_template_name 	0.00190876004465631
12687020	23171	rtrim from replace	select substring(name2,0,charindex('@@',name2)) from table 	0.344144632346913
12698572	19282	oracle: add incremental ids for unique combination of two other columns	select uid, type, url,        row_number() over(partition by uid, type order by url) as seqid     from yourtable 	0
12698884	21469	mysql: unique text field using additional hash field	select md5('1234') select sha('1234') select sha1('1234') select sha2('1234',224); 	0.028162819807144
12708023	12852	summing multiple order by columns	select      t.type,     sum(t.external_account) from (     select       case t.type         when 'prolong' then 'prolong + reg + reg2'         when 'reg' then 'prolong + reg + reg2'         when 'reg2' then 'prolong + reg + reg2'         else t.type       end as type,       t.external_account     from       u_contracts c,       u_data u,       u_transactions t     where       c.user_id = u.id       and t.contract_id = c.id       and t.nulled =0       and date (c.init_date) < date (u.dead)       and u.dead is not null       and t.type != 'repay' ) t  group by       t.type order by   field( t.type, 'initial', 'comission', 'overpay', 'penalty', 'penalty2' ); 	0.0167274183687586
12712782	2553	sql subqueries in from clause	select count(*)        from @testtable test0       where              exists (select 1 from @testtable test1 where test0.id = test1.id and test1.id % @i = 0)             exists (select 1 from @testtable test2 where test0.id = test2.id and test2.id % @j = 0)             exists (select 1 from @testtable test3 where test0.id = test3.id and test3.id % @k = 0) 	0.737077869634444
12718615	26900	select similar ip addresses - ignore last 3 digits	select      group_concat(username) as names,      substring_index(ips, '.', 3) as ips     count(*) as instances  from     users group by      substring_index(ips, '.', 3) having     count(*) > 1 order by     instances desc 	0.000273020336025348
12719496	41117	sql query with count	select l.id, l.name, count(li.item_id) as item_count  from list l left join list_item on l.id = li.list_id group by l.id 	0.530145980730025
12722298	12662	group-by expression must contain at least one column that is not an outer reference	select solutionname     from  table_view group by solutionname 	0.321461069322233
12723806	39852	sql - group results by time interval	select eventtime/5,count(*) from   evalhubsupply group by eventtime/5 	0.0713162234733647
12726450	31513	oracle regexp_replace uppercase replacement string	select regexp_replace('src=/i/uie_v2/js','(.*)(/uie_v2/)(.*)', '\1') ||   upper(regexp_substr('src=/i/uie_v2/js','(/uie_v2/)')) ||    regexp_replace('src=/i/uie_v2/js','(.*)(/uie_v2/)(.*)', '\3') from dual 	0.76405458099758
12745782	32985	select datetime column of table in 24 hour format with sql	select convert(varchar(24), receivedon, 121) 	0
12751483	6922	sql return count() of rows separated by criteria	select max(id), date, customer_id, count(*) from t group by date, customer_id order by 1 	4.81091025852002e-05
12774238	37810	hierarchical product count using nested sets in mysql	select count(distinct productid) from categories join products_to_categories using (categoryid) join products using (productid) where categories.left >= {left value of category in question} and categories.right <= {right value of category in question} 	0.662287813485495
12797152	5722	mysql concat request and string substraction	select concat_ws(";", id, user_id, left(ticket,length(ticket)-length(user_id))) from table1; 	0.504978836398072
12799824	35131	how to get table name, column name, column describe, column value in sql server 2008	select  'users' as tablename,         'username' as columnname ,         'the user name' as columndescribe,         username as columnvalue  from users where [userid]=1  union all select  'users' as tablename,         'userpwd' as columnname ,         'the user name' as columndescribe,         userpwd as columnvalue  from users where [userid]=1 	0
12801191	5919	returning max value of select statement sql	select count(`name`) as `num` from `sometable` where `someid` = xxx group by `field` order by `num`  desc limit 1 	0.0354659851893159
12802155	32269	making sql find the nearest result if it can't find the exact search term?	select d.*, abs(d.traywidth - user_search_inputted_width) as width_abs from delyn d order by width_abs limit 20; 	0.037860802248199
12814943	27176	drop all unique keys from a table - t-sql	select      distinct 'alter table mytable drop constraint '+o.name  from sys.objects o      join sys.columns c on o.parent_object_id = c.object_id and o.type='uq'      join sys.tables t on c.object_id = t.object_id where t.name = 'mytable' 	6.55320324008512e-05
12814949	30046	get result from sql with ignore some numbers	select  author from dle_photo_post where ug not in('5','0') and moder ='0' 	0.00101804490260543
12819206	35660	left join for on col to multi col	select t.date,        a.acc_name acc_name1,        b.acc_name acc_name2,        c.acc_name acc_name3,        d.acc_name acc_name4 from d002 t left join d001 a on a.acc_id = t.acc_id_1 left join d001 b on b.acc_id = t.acc_id_2 left join d001 c on c.acc_id = t.acc_id_3 left join d001 d on d.acc_id = t.acc_id_4 	0.674901964645827
12821039	15923	sql,php, multiple tables, recordsets, advise needed	select    tbl_bands.*,   tbl_albums.*,   tbl_tracks.*,   tbl_tabs.* from    tbl_bands left join    tbl_albums on    tbl_bands.bid = tbl_albums.bandid left join   tbl_tracks  on    tbl_albums.aid = tbl_tracks.albumid left join   tbl_tabs on   tbl_tracks.tid = tbl_tabs.trackid where order by  limit   0, 1000 	0.718998843911622
12824111	27440	how do i make a query return nothing when there are no conditions?	select * from table where 1 = 0 or (real conditions) 	0.449658346347566
12827085	5335	count parts of total value as columns per row (pivot table)	select  trunc(f.create_date, 'dd') as created ,       sum(case trunc(f.process_date, 'dd') - trunc(f.create_date, 'dd')                   when 0 then 1 end) as diff0days    ,       sum(case trunc(f.process_date, 'dd') - trunc(f.create_date, 'dd')                   when 1 then 1 end) as diff1days    ,       sum(case trunc(f.process_date, 'dd') - trunc(f.create_date, 'dd')                   when 2 then 1 end) as diff2days    ,       ... from    files f  group by          trunc(f.create_date, 'dd') 	0
12836195	36457	how to drop foreign key constraint	select cast(f.name as varchar(255)) as foreign_key_name , cast(p.name as varchar(255)) as parent_table from sysobjects f inner join sysreferences r on f.id = r.constid inner join sysobjects p on r.rkeyid = p.id inner join syscolumns rc on r.rkeyid = rc.id and r.rkey1 = rc.colid where f.type = 'f' 	0.00103137000380748
12839924	1529	sql server: split a single row into 2 rows	select id,     case       when ( isocode like '% or %' ) then left(isocode, charindex('or',                                                         isocode) - 1                                           )       else isocode     end as isocode,     data  from   tbl  union  select id,         right(isocode, len(isocode) - ( charindex('or', isocode) + 2 ))as isocode         ,         data  from   tbl  where  isocode like '% or %' 	0
12849132	26517	use function result as columns in query with postgresql	select (get_sticker(a_value)).*, * from foo_bar; 	0.764623988402221
12850285	25250	creating an array from mysql where column equals id column	select id_1, group_concat(id_2) 	0.000595406963561367
12862525	9151	pl/sql: how can i calculate the age knowing a column called birth_date?	select id, months_between(sysdate, birth_date) / 12 age from my_table; 	0.000452734824970984
12874669	10826	sql and php wall	select * from posts where `by` in (select `to` from following where `by` = user_id) 	0.368451645662222
12875936	35927	get mutiple pictures in one row from other table	select *, group_concat(pic.picture) from picture as pic  inner join news as news on pic.newsid = news.newsid group by news.newsid 	0
12881165	25574	combine same column name data of two different tables in sql to a result set including null	select    resourcei as rs, sum (createdlogin) as countcreated,  sum (deletedlogin) as countdeleted from  (select   objdate,  resource ,  1 as deletedlogin,  0 as createdlogin   from  resource_deleted  union all  select objdate,  resource ,  0 as deletedlogin,  1 as createdlogin    from  resource_created )  table_all where objdate between to_date('4-oct-12') and to_date('6-oct-12') group by resource 	0
12882520	28155	2 counts in same query but different conditions	select      tshops.shopid,      tshops.officialname,      tsuppliershopinfo.contactname,        tsuppliershopinfo.contactmail,      count(distinct tresults.pid) as aantalvanpid,     count(distinct          case when tresults.price < tsupplierproducts.lowestprice then tresult.pid end         ) as aantalvanpid_2 from     tsupplierproducts      inner join tresults on tsupplierproducts.pid = tresults.pid        inner join tsuppliershopinfo on tresults.shopid = tsuppliershopinfo.shopid     inner join tshops on tsuppliershopinfo.shopid = tshops.shopid where      tsupplierproducts.supplierid = 2     and      tresults.starttime between          date_sub(curdate(), interval 14 day) and date_add(curdate(),interval 1 day) group by      tshops.shopid,      tshops.officialname,      tsuppliershopinfo.contactname,      tsuppliershopinfo.contactmail 	0.000804367292583164
12884826	3842	mysql - sum of one column in one table with other column in other table	select sum(sm) from    (select sum(marks) sm from sums1 where idno=1    union    select sum(marks) sm from sums2 where idno=1 ) ss 	0
12898083	28718	get sql results from same column multiple times	select t1.someid,     max(case when t2.id = 1 then t2.description end) name,     max(case when t2.id = 2 then t2.description end) address,     max(case when t2.id = 3 then t2.description end) comments from table1 t1 left join table2 t2     on t1.someid = t2.someid group by t1.someid 	0
12899150	21869	mysql - in operator (with exact values)	select * from argument_user a inner join argument_user b on a.argument = b.argument left outer join argument_user c on a.argument = c.argument and c.user_id not in (1,2) where a.user_id = 1 and b.user_id = 2 and c.user_id is null 	0.396595709117969
12900307	17991	two subqueries added to addition complex mysql query returning no records	select i.*, o.organ_name, o.organ_logo, vtable.* from heroku_056eb661631f253.op_ideas i left join   (select v.idea_id, cc.*,     count(v.agree = 1 or null) as agree,     count(v.disagree = 1 or null) as disagree,     count(v.obstain = 1 or null) as abstain     from op_idea_vote v  left join    (select idea_id as id,count(*) as ccount      from op_comments cco     group by cco.idea_id     ) as cc on cc.id = v.idea_id   group by v.idea_id   ) as vtable on vtable.idea_id = i.idea_id   left join op_organs o on i.post_type = o.organs_id where idea_geo = 'international'; 	0.305614514252437
12904498	37321	join type to use for reading from tables that contain templates and different numbers of items?	select      q.questionid,     q.questiontext,     a.custid,     a.answer, from      surveyanswers a           right outer join surveyquestions q         on a.questionid = q.questionid     and         a.custid = @customerid; 	0
12911954	16215	returned datatable from sql command "show table status"	select * from information_schema.table where table_schema = 'db_name' and table_name = 'table_name'; 	0.00131440466943987
12921907	7316	update a whole column based on 2 columns of a different table	select   case when (effectivethrutime is null and senttime >= effectivefromtime) then orgid   when (effectivethrutime is not null and senttime >= effectivefromtime) then orgid   when (effectivethrutime is not null and senttime between effectivethrutime and   effectivefromtime) then orgid   end as orgid   from ac   left join op   on ac.clinicalidentifier=op.clinicalidentifier   where ac.senttime>op.effectivefromtime    and ac.senttime<=isnull(op.effectivethrutime,ac.senttime) 	0
12923140	30307	php/mysql query join	select     item.name,     group_concat (tags.tag seperator ',') as tags from     item     left join tagitem on tagitem.itemid = item.id     left join tag on tagitem.tagus = tag.id where     item.id = 2 	0.647877282071332
12923483	17041	sql server group by guid but order entire query by most recent in group	select y.id, y.data, y.date, y.guid from   (select max(a.date) as date, a.guid     from mytable a     group by a.guid)x,   (select id, data, date, guid,      row_number() over(partition by guid order by guid) as rn      from mytable)y where x.guid = y.guid order by x.date desc, y.date desc; 	0.00475236521376093
12929191	33379	join two sql result	select first.id, first.name, second.note from first left join second on first.id = second.id order by first.id 	0.161096962854543
12934160	29472	display multi columns from the one table	select   emp_id,   max(case when month_end = 'jan' then salary end) 'jan',   max(case when month_end = 'feb' then salary end) 'feb',   max(case when month_end = 'mar' then salary end) 'mar' from emps group by emp_id 	0
12937961	10735	mysql group by and conditions	select parts, parts_number, option from parts group by parts, parts_number, option 	0.328690476898744
12938302	31562	sql - select most 'active' timespan fromdb	select datepart(hour, the_column) as [hour], count(*) as total from t group by datepart(hour, the_column) order by total desc 	0.00394595200570617
12939227	17415	find column value by dividing with sum of a column	select id,        field1,        (sum(field1) over() / field1) as field2 from yourtable 	4.88810246691342e-05
12957447	20382	rules of thumb when storing large amounts of data in a database	select  object_name(sc.[id]) tablename,     count(sc.name) numbercolumns,     sum(sc.length) + 96 maxrowlength,     8060 / (sum(sc.length) + 96) as recordsperpagefrom  syscolumns sc     inner join sysobjects so on sc.[id] = so.[id]where  object_name(sc.id) = 'blah'group by object_name(sc.[id])order by sum(sc.length) desc 	0.00541680828584238
12957781	36764	indexing sql for between query with only one match?	select * from table1 where col1 =      (select max(col1) from table1 where col1 <= 8) and col2 =      (select min(col2) from table1 where col2 >= 8) 	0.0207761175870825
12958828	21023	adding and multiplying count() of several tables	select a.id,        a.aa + (2 * b.bb) + (3 * c.cc) from   (     select id, count(*) aa     from table1     group by id   ) a left join   (     select id, count(*) bb     from table2     group by id   ) b on a.id = b.id   left join   (     select id, count(*) cc     from table3     group by id   ) c on a.id = c.id 	0.00210699495535881
12980075	33356	connecting table with multiple foreign keys in mysql	select u.displayname from users u inner join owners o on     o.primaryitowner = u.username     or o.secondaryitowner = u.username     or o.primarybusinessowner = u.username     or o.secondarybusinessowner = u.username 	0.003144308107367
12982277	25618	condensing a dataset on nulls	select fk,max(col1),max(col2),max(col3),max(col4) from dbo.yourtable group by fk 	0.328339366274262
12984093	3729	selecting mysql datetime in a range	select * from requests   where date_created between date('2012-10-01 00:00:00')                              and date('2012-11-01 00:00:00'­) 	0.00162066305893878
12985162	31661	joining two tables, two columns while displaying multiple rows as a single row	select            f1.firstname         , f1.lastname         , f2.firstname         , f2.lastname     from matches as m         inner join fighters as f1             on f1.fighterid = m.fighteroneid         inner join fighters as f2             on f2.fighterid = m.fightertwoid 	0
12992714	6184	php/mysql query for row index (not id) in a table	select position from (    select    name, @rownum:=@rownum+1 position    from chapters, (select @rownum:=0) r    order by id ) as position where name = 'how are you?' 	0.00971727645735954
12995863	2021	product sales report weekly monthly	select p.description, psw.qtysum, psw.opsum, psm.qtysum, psm.opsum from products p left join   ( select sw.product_id, sum( sw.qty ) as qtysum, sum( sw.`order price` ) as opsum      from orders sw      where week( sw.`purchase date`) = week( current_date )     and year( sw.`purchase date`) = year( current_date )     group by sw.product_id ) psw    on p.id = psw.product_id left join   ( select sm.product_id, sum( sm.qty ) as qtysum, sum( sm.`order price` ) as opsum      from orders sm      where month( sm.`purchase date`) = month( current_date )     and year( sm.`purchase date`) = year( current_date )     group by sm.product_id ) psm    on p.id = psm.product_id 	0.00211905312066674
13005447	9527	getting unix time with number	select   unix_timestamp('2012-10-01' + interval c.day - 1 day) unix_ts_day,   count(v.site_id) from   calendar c left join (   select * from visitors     where site_id = 16 and date(created) between '2012-10-01' and '2012-10-31'   ) v   on dayofmonth(v.created) = c.day group by   unix_ts_day 	0.00142736765231651
13006545	22128	sql query guaranteed to return empty	select * from <table_name> limit 0 	0.398464590102769
13023731	34597	multiple as statements from a single column	select     case t.number when 4 then t.text else '' end as imafour,     case t.number when 6 then t.text else '' end as imasix,     .... from table t 	0.0038915932555351
13030013	17197	counting rows matching criteria in mysql join , union >= and <=?	select  *, (if(a<=7 and a>=5,1,0) + if(b<=19 and b>=17,1,0) + if(c<=29 and c>=27,1,0)) as totalmatch from table having totalmatch >=2 	0.0150605477123708
13038187	35350	passing user id to nested query	select   u.userid,   u.username,   u.mail,   u.name,   u.lastname,  u.starting_year,   u.userid as uidd  from   userdb.users as u  where   u.userid not in (     select        u.userid      from        maildb.lists as l,        maildb.list_subscriptions as s,        userdb.users as u      where        u.userid = u.userid        and l.listid = '$list_id_to_lookup'        and s.userid = u.userid        and s.listid = l.listid     )  order by   u.starting_year desc, u.lastname, u.name; 	0.202714230774184
13052209	14010	how to write a sql query to generate a report	select name as 'call name',           submitted as 'proposals submitted',          sum(case when maxstatus > 1 then 1 else 0 end) as 'proposals reviewed' from    (select cfp.name,      sum(case when ps.status_id = 1 then 1 else 0 end) as submitted,     max(ps.status_id) as maxstatus     from calls_for_proposals cfp     left join proposals p on cfp.id = p.call_id     left join proposal_statuses ps on ps.proposal_id = p.id     group by cfp.name) as s group by name, submitted 	0.278782210983338
13055760	20418	two counts in one query	select  (  select count(id_user)  from   stalkers where id_user =  ".$id." ) as user_stalkers, (  select count(id_user_stalkers)  from   stalkers where id_user_stalkers = ".$id." ) as user_is_stalked 	0.00766084116948989
13066141	22750	sql - how to select two different counts from different level of join?	select pub.pub_id, count(p.article_id), count(distinct j.article_id)  from publication pub inner join journal j on pub.journal_id=j.journal_id left join published p on j.article_id=p.article_id group by pub.pub_id 	0
13082632	20010	ηow to count employee readings in current month	select reader.employeeid, count(reading.readingid) from a2_meterreader reader, a2_reading reading where reader.employeeid = reading.employeeid and year(reading.daterecord) = year(sysdate) and month(reading.daterecord) = month(sysdate) group by reader.employeeid 	0.00019885868085495
13099319	33299	select row dependent on other rows in the table	select * from products_categories where category_id in (2,3) having count(distinct(id)) = 2 	0
13110649	3808	how to obtain a data set from postgresql 9.0 function ("stored procedure")	select * from get_all_members() 	0.136957632010807
13112759	26052	how to select a record that is between two dateranges and two input parameters startdate and enddate in sql server?	select * from table1 t1   inner join combinations c on t1.id=c.table1id inner join [group] g on c.groupid=g.id   where t1.date<= @enddate and t1.date>= @begindate  and g.begindate <=@enddate and g.enddate >= @begindate and t1.date between g.begindate and g.enddate 	0
13124165	36785	separating column into two separate columns	select      case when charindex(',',name) > 0              then left(name, charindex(',',name)-1 )              else name end,     case when charindex(',',name) > 0              then ltrim(substring(name, charindex(',',name)+1, len(name) ))              else null end    from yourtable 	9.32021001233555e-05
13125141	14903	select dates between two unix timestamps	select * from users where user_date between   extract(epoch from date '2012-10-21') and   extract(epoch from date '2012-10-24' + interval '1 day'); 	0
13127389	36414	sql subquery from same data table	select     emp.employeeid          "empid",     emp.firstname           "empfirst",     emp.lastname            "emplast",     dept.departmentname     "deptname",     deptmgremp.firstname    "mgrfirst",     deptmgremp.lastname     "mgrlast" from     dbo.employees as emp     left join dbo.departments as dept     on emp.departmentid = dept.departmentid     left join dbo.employees as deptmgremp     on dept.managerid = deptmgremp.employeeid 	0.00378582925796956
13129470	26851	can not select binary field whit php	select * from `pt_peers` where `info_hash` = x'7f398565868f7f08f71d236b88e4e433d2311de8' 	0.106835975551733
13134123	23461	corelating two mysql tables according to time	select t.actionid,t.stateid,a.type action_type,s.type state_type  from  (select actions.actionid,max(states.stateid) stateid from actions, states where states.time < actions.time group by actions.actionid)as t join  actions a on t.actionid=a.actionid join states s on t.stateid=s.stateid 	0.000936816492171709
13135347	38858	sql statement returns wrong values (top n ... order by)	select top n ... from (   select ...   from table   where ...   order by ... ) 	0.163676477788854
13136746	741	how can i query in mysql-table(where lat and long stored) that which are the nearest location to inputed location(lat and long)?	select * from gps_location_table t  where     t.x between 20.134554 and 20.334554 and t.y between 56.11455255 and 56.31455255 order by      sqrt((t.x - 20.234554)*(t.x - 20.234554) + (t.y - 56.21455255)*(t.y - 56.21455255) desc 	0.613628968611291
13146304	14602	how to select every row where column value is not distinct	select emailaddress, customername from customers where emailaddress in (select emailaddress from customers group by emailaddress having count(*) > 1) 	0.000202996544290459
13150486	1013	get integer part of number	select floor(value) 	0.000388180105912405
13167464	33007	query returning consecutive rows with matching value	select count(*) as num from data_point where creation_datetime > (   select max(creation_datetime)   from data_point   where data_point <> 0 ) 	0.000568373284708961
13168066	39045	how do i transpose rows and columns (a.k.a. perform a pivot) in postgresql only for rows and columns with a minimum count()?	select   year,   max(case animal when 'kittens' then avg_price end) as "kittens",   max(case animal when 'puppies' then avg_price end) as "puppies" from (   select     animal,     year,     count(*) as cnt,     avg(price) as avg_price   from tab_test   group by     animal,     year ) s where cnt >= 3 group by   year ; 	0
13177591	32930	select matching rows as columns	select  a.surveyid,         max(case when c.questiontext = 'name' then b.answertext else null end) name,         max(case when c.questiontext = 'e-mail' then b.answertext else null end) email from    survey a         inner join answer b             on a.surveyid = b.surveyid         inner join question c             on b.questionid = c.questionid group by a.surveyid 	0.000446710695075712
13181219	15035	selecting data from specfic times	select * from your_table where ts_col between               dateadd(hour, 6, dateadd(day, datediff(day, 0, getdate()), -1))                 and dateadd(hour, 6, dateadd(day, datediff(day, 0, getdate()), 0)); 	0.000450731045068638
13182015	17790	sql if null show 0	select      sales_id,     ifnull(totalbuy, 0),     ifnull(totalsell, 0),     ifnull(totalbuy, 0) + ifnull(totalsell, 0) as total from (     select         sid as sales_id,         sum(case when side = 'buy' then 1 else 0 end) as totalbuy,          sum(case when side = 'sell' then 1 else 0 end) as totalsell      from          ( select 'sales1' as sid union select 'sales2' union select 'sales3' union select 'sales4' ) mysalesids     left outer join car_orders       on sales_id = sid     group by        sales_id ) q order by total desc limit 0, 10; 	0.0812230440453315
13184949	27060	join columns from multiple tables	select r.name, b.title, br.rating from reviewer r join bookreview br on br.reviewerid = r.reviewerid      join book b on b.isbn = br.isbn where r.employedby is null or r.employedby = '' 	0.00347131904395342
13194453	8856	leftouter join in sql	select u.column1, uai.column1, uai.keycolumn2 from user u left outer join user_account_map uam on u.user_id  = uam.user_id left outer join user_account_info uai on u.account_number  = uai.account_number 	0.616332153242864
13198395	34088	select with sql the oldest payment associated to a list of persons	select * from (    select id_person,            payment_date,           row_number() over (partition by id_person order by payment_date) as rn    from payment    where id_person ind (1,2,5,10) ) t where rn = 1 	0.000156107728702798
13213624	32954	how to find percentages of values in sql?	select  hero, avg(pointearned > 0) p from    gamestatistics group by         hero order by         p desc 	0.0177435809534851
13214442	23423	quering multiple tables	select inventory.inven_id, ... 	0.197072405155672
13220121	8468	sql , count equivalent values in each column	select country, count (*) from <table_name> where url_id = 3404 group by country 	0.00333951328178293
13221154	39206	how can i get join not duplicate?	select p.pno ,coalesce(l.cdate,t.ldate,'2012-10-22') as ldate ,coalesce(l.lstart,t.cin) as lstart ,coalesce(l.lstop,t.cout  ) as lstop from peopleall p left join leave l on l.lno=p.pno and l.ldate='2012-10-22' left join ftime t on t.tno=p.pno and t.cdate='2012-10-22' 	0.0436315932897009
13227051	18471	execute a subquery in mysql that returns multiple rows?	select  datediff(curdate(), due), due  from    checkout join people              on checkout.p_id = people.p_id where   case             when date_sub(date_add(curdate(),interval 4 month), interval 3 month)                      >= checkout.checktime             then 1             else 0          end  order by checkout.due 	0.132784329487398
13229138	25374	get the last 4 months of the year in mysql?	select date_format(curdate(), '%m') month_name union select date_format(date_add(curdate(),interval -1 month), '%m') month_name union select date_format(date_add(curdate(),interval -2 month), '%m') month_name 	0
13231501	10068	sql sum repeats from sql query?	select i.car_info ,count(1)   from inventory i    join sales s on s.car_id = i.car_id where s.sales_id = 'sales_id1' group by i.car_info 	0.13492557010006
13232486	25113	grouping / multiple queries in one report in microsoft access report	select 1 as sortorder, contact, details, status1, status2 from contactstable  where status1 is null  union all select 2 as sortorder, contact, details, status1, status2 from contactstable  where status1 = "a" union all select 3 as sortorder, contact, details, status1, status2 from contactstable  where status1 = "b" union all select 4 as sortorder, contact, details, status1, status2 from contactstable  where status2 = true 	0.570619184037963
13242004	37294	how do i display different values as different columns in sql?	select s.userfirstname + ' ' + s.userlastname as name,         [site1name],        [site2name] from        (select s.userfirstname + ' ' + s.userlastname,                sitename,                sitevisits         from users s          inner join usage j1            on s.userid = j1.userid        ) pivot (sum(sitevisits) for sitename in ([site1name],[site2name])) as p 	0
13249503	35727	sql xml query from column	select     id,     filename = objprm.value('@value', 'varchar(100)') from @t1 cross apply x.nodes(' 	0.0432695839506621
13265250	22376	query to return pokemon with hp by type	select p2.maxhp, p2.type, p1.name  from `pokemon` p1 inner join (    select type, max(hp) maxhp    from pokemon    group by type ) p2 on p1.type = p2.type and p1.hp = p2.maxhp 	0.591490804807786
13277670	1659	select company names with more than x orders	select companyname     from orders     join customers on orders.customerid = customers.customerid group by companyname   having count(companyname) > 3 	5.289185967131e-05
13282999	31719	using the sum function on an indirectly joined table. .	select sum(distance) from tblc join tblb on tblc.workoutid = tblb.workoutid          and tblb.userod = 1 	0.148247095416331
13285105	10553	mysql search based on user weightage	select name from customers  order by (location = 'fort worth, tx')*10 + (age > 21)*3 desc  limit 0,20; 	0.00522621955736287
13285648	30966	mysql order by 2 colums (date/frequency)	select * from `favorites`  where `employee_id` = 1 and `frequency` >= 6 order by (date_sub(curdate(),interval 30 day) <= `lastchanged`) desc,     `frequency` desc  limit 0,6 	0.0307612176776033
13288742	19665	linking ids of the same row to other tables	select map.transition_set_variable_id,         map.transition_id,        variable.name,        variable2.name,        value.name from variables as variable    inner join mapping as map on variable.variableid = map.variableid   left join variables as variable2 on map.to_variableid = variable2.variableid   left join values as value on tsv.to_valueid = value.valueid order by map.transitionid, variable.variableid 	0
13295843	34961	returning distinct sql query based on tag database based on and	select t.topic_id from topics_keywords t inner join keywords k on t.keyword_id = k.keyword_id where k.keyword in ('keyword1', 'keyword2') group by t.topic_id having count(distinct k.keyword_id) = 2 	0.000142629875952133
13314323	1257	sql: join on two tables where on column is null	select bug_id, `desc`, dev.assigned_to, qa.qa_contact  from bugs inner join profiles as dev on bugs.assigned_to = dev.userid left outer join profiles as qa on bugs.qa_contact = qa.userid 	0.0273979775030357
13315408	32655	2 while loops in 1 html table	select n1.*, a1.ed_name addedby_name, a2.ed_name lasteditor_name from n1news as n1 inner join a1editors as a1 on n1.n1_addedby=a1.ed_id left join a1editors as a2 on n1.n1_lastedit=a2.ed_id where n1_co=$ed_co order by n1_id limit $show,$limit 	0.0201195215355736
13315950	38879	select article with 3 or more comments	select article.*, count(comment.com_id) as comment_count from comments left outer join article on article.art_id = comments.com_article group by article.art_id having comment_count > 3 	0.0510874923193389
13331621	38054	sql query to get sql year version	select     'sql server year ' +      case substring(convert(varchar(50), serverproperty('productversion')), 1, 2)           when '8.' then '2000'           when '9.' then '2005'           when '10' then '2008'           when '11' then '2012'     end 	0.0166898175533093
13335223	37820	sql: separate column names after two inner joins	select banhammer_bans.id as bans_id, banhammer_players as players_id, ... from banhammer_bans inner join banhammer_players as player     on banhammer_bans.player_id = player.id inner join banhammer_players as admin     on banhammer_bans.creator_id = admin.id order by created_at desc 	0.00962143264670929
13343990	22136	mysql return based on a difference	select cust_first, cust_last from customer where cust_id in (     select cust_id     from session     join order on session.ses_id = order.ses_id     group by cust_id, session.ses_ipaddress      having count(1) > 1 ) 	0.000450710643320431
13348244	34883	mysql query to sum all distinct values	select uid_to, sum(count) as sum from your_table group by uid_to 	0.00256751822994181
13360377	23505	error renaming a temporary table	select * into #newname from #oldname drop table #oldname 	0.470136562295023
13365982	7634	select last group of data	select * from t cross join      (select max(object_id) maxobject_id from t) maxt where object_id = maxt.maxobject_id and       generated_at > (select max(generated_at) from t where object_id <> maxt.maxobject_id) 	0.000425648668232357
13368152	28320	query to find if a foreign key is set	select b.idtablea_fk, b.idtableb , if (     (select a.idtableb_fk          from (tablea as a)          where a.idtablea = b.idtablea_fk     ) = b.idtableb, true, false ) as is_set from (tableb as b) 	0.000919039454365273
13374705	38683	count purchases from 2nd table	select u.id,         u.username,         (select count(1) from purchases p where u.id=p.user_id) as purchases from user u 	0.00043039882378512
13380218	17742	link sql results to each other	select u.id, u.first as [first name], u.last as [last name], t.tag as [tag number], t.pass as [password], t.active from [user] as u left join [tags] t on u.id=t.userid order by u.[id] asc 	0.000217862669737456
13380839	35489	mysql distinct keyword not showing distinct rows	select distinct 	0.0719496460007731
13386920	2762	mysql select dates within calendar week	select * from items where last_update >= curdate() - interval dayofweek(curdate())-1 day and last_update <= curdate() + interval 7 day - dayofweek(curdate()) 	0.00156353141065765
13392189	16324	remove column from mysql select	select        name from orders  group by name having count(custname) >= 2; 	0.00438246512341733
13394480	37496	sort on two columns	select v1.stamp, v1.host from visits as v1     left join (select min(date) as firstvisit, host               from visitor as v2                group by v2.host               order by firstvisit desc               limit 1000) as j        on v1.host=j.host         order by firstvisit desc, v1.host, v1.date desc        limit 100; 	0.0016732185309609
13395965	3426	mysql average on a sum	select t1.site, avg(sumtime) from (     select site.title as site, sum(time) as sumtime from log     inner join site on site.id = log.sid     and log.date between '2012-11-14' and '2012-11-15'     group by site, date(log.date) ) as t1 group by t1.site 	0.00474280676156358
13399182	17110	count records in same column with and without parameter	select part#,         count(distinct case when make = '1' then application# end) make1_apps,        count(distinct application#) total_apps from   [mytable] group  by part# having count(distinct case when make = '1' then application# end)      = count(distinct application#) order  by part#; 	0.00153186052878994
13399355	2533	combining two columns into one column with text added	select    'there were a total of '   + cast(count(*) as varchar(10))    + ' invoice(s) on '   + convert(varchar(12), yourdatecol, 107) from invoices group by convert(varchar(12), yourdatecol, 107) 	0
13399970	18619	mysql or and and operation	select ... where (name1 in ('a', 'b')) and (name2 = 'b') select ... where ((name1 = 'a') or (name1 = 'b')) and (name2 = 'b') 	0.785153434423868
13419382	18195	need to find a random record from one table, then join another table with this record	select top 1 sl.lotid, sl.participantid, p.firstname, p.lastname  from sample_lots sl  inner join participants p on sl.participantid = p.participantid with (nolock) where     cast(created as date) = '2012-11-16'     and     sl.participantid not in     (         select participantid from sample_winners with (nolock)         where             participantid is not null             and             cast(thisdate as date) = '2012-11-16'     )     and     sl.participantid in     (         select participantid from sample_participants with (nolock)         where             participationconfirmed is not null     ) order by newid() 	0
13421222	17226	in t-sql, how to take a value of a row, based on conditions on a second column?	select invoicenumber, accountnumber from  (     select           row_number() over(             partition by invoicenumber               order by sum(amount) desc, accountnumber desc         ) rownumber,         invoicenumber,         accountnumber     from vinvoice_table     group by invoicenumber, accountnumber  )inv where rownumber = 1 	0
13421227	8530	how to join a table with multiple foreign keys from the same table?	select      m1.modename,     m2.modename,     m3.modename,     m4.modename,     m5.modename from modes m left join ref m1 on m1.modeid = m.mode1 left join ref m2 on m2.modeid = m.mode2 left join ref m3 on m3.modeid = m.mode3 left join ref m4 on m4.modeid = m.mode4 left join ref m5 on m5.modeid = m.mode5 	0
13436613	1899	display the name and max age	select     dr_drvname as "name",     trunc(months_between(sysdate, dr_birthdate) / 12) as "highest age" from ( select     dr_drvname,     dr_birthdate from     driver order by     dr_birthdate ) where     rownum = 1; 	0.000163752063059711
13441606	1688	sql time clock data manipulation	select      a.uid,      convert(date, clock) 'clockdate',      min(clock) 'clockin',      max(clock) 'clockout' from      attendancetbl  group by uid, convert(date, clock) 	0.204594930290754
13443664	38027	mysql query to find most similar numerical row	select   u2.user_id from     (users u1 join scores s1 using (user_id))     join (users u2 join scores s2 using (user_id))       on s1.item_id  = s2.item_id      and u1.user_id != u2.user_id where    u1.user_id = ? group by u2.user_id order by sum(abs(s2.score - s1.score))        + abs(u2.self_ranking - u1.self_ranking) desc 	0.000717721547686831
13480309	12114	how can i use fields from a previous join in the where criteria of my derived table?	select fbs_household_id, fbh_file_no, c1.fbc_last_name, c1.fbc_first_name from fbs_household left join fbs_client c1  on c1.fbc_household_id = fbs_household_id  left join fbs_client c2 on c1.household_id = c2.household_id and (c1.dob > c2.dob      or c1.dob = c2.dob       and c1.fbs_client_id > c2.fbs_client_id)  where c2.dob is null 	0.00108824767710047
13485448	37580	mysql select rows by a key or fall back to select by default key	select  distinct         coalesce(b.id, a.id) id,         coalesce(b.`group`, a.`group`) `group`,         coalesce(b.`text`, a.`text`) `text`,         coalesce(b.language, a.language) language from   tablename a        left join         (             select id, `group`, `text`, language             from tablename             where language = 'de'          ) b on a.id <> b.id and a.`group` = b.`group` 	0.000296003164553749
13493240	29381	oracle - sql - count multiple fields	select count(strtest1), count(strtest2), count(strtest3) from your_table 	0.116245103896835
13493388	30059	is whether a replication is continuous queryable anywhere?	select      agent.*,     case when exists(         select *         from msdb.dbo.sysjobsteps step         where agent.job_id=step.job_id         and step.step_id=2         and step.command like '%-continuous%')         then 1         else 0     end as continuous from distribution.dbo.msmerge_agents agent 	0.505664761771022
13496453	294	grouping null and empty values as one in sql	select categories,  case when categories is null or categories = ' '  then 'nocategory' else categories end as grouped, count(*)  from products  group by grouped 	0.00800508155659146
13505268	41184	one to many relationship in android sqlite	select subjects.* from teachers_subjects join subjects                        on teachers_subjects.subject_id = subjects._id where teachers_subjects.teacher_id = ? 	0.0586776763963615
13513187	2558	mysql related 'projects' query	select      p.*,     (         ifnull(themes.matches, 0) + ifnull(platforms.matches, 0) + ifnull(clients.matches, 0)     ) as score from `project` p left join (     select t2.project_id, count(*) as matches from `project_theme` t1, `project_theme` t2     where        t1.theme_id = t2.theme_id and t1.project_id = 1       group by t2.project_id ) themes on p.id = themes.project_id left join (     select f2.project_id, count(*) as matches from `project_platform` f1, `project_platform` f2     where        f1.platform_id = f2.platform_id and f1.project_id = 1       group by f2.project_id ) platforms on p.id = platforms.project_id left join (     select p2.id, count(*) as matches from `project` p1, `project` p2     where        p1.client_id = p2.client_id and p1.id = 1       group by p2.id ) clients on p.id = clients.id group by p.`id` having score > 0 order by score desc; 	0.12010685082861
13551041	28512	concat a string to select * mysql	select concat(field1, '/'), concat(field2, '/'), ... from `socials` where 1 	0.126968021047274
13559421	6696	sql oracle union with null values	select nvl(a, lag(a) over (order by rownum)), b, c from (   select a, b, c from x   union    select a, b, c from y ) 	0.405009117434271
13561748	1107	sql - how to get max count for 2 tables sql	select max(c) from (select leg.t#,count(leg.leg#) c from trktripleg leg,trktrip trip  where leg.t#  = trip.t# and trip.l#='10001'  group by leg.t#); 	0.000921525684629754
13577521	5110	query result printing in categorized list	select col, keyword from ( select tname as keyword, 'tutors' col from t union select sname as keyword, 'subjects' col from sub union select cname as keyword, 'city' col from c union select iname as keyword, 'institutes' col from i  ) s where keyword like '%$querystring%'  limit 10 	0.36885660096975
13578983	16069	merge result of two sql queries in two columns	select a.c1-b.c2 as res  from ( select count(*) as c1 from users group by name ) a join ( select count(*) as c2 from user2 group by name ) b on 1=1  	9.98633536299464e-05
13584363	38822	mysql compare emails and match even if one upper the other lowercase	select * from yourtable where lower(col1)=lower(col2); 	0.000370688368373267
13588408	7265	sql and and or in 1-n mapping table	select id  from yourtable where map_id in (1,2) group by id having count(distinct map_id)=2  	0.356152614315508
13591798	39049	join two tables in such way that i can get all items for all dates	select  dt.purchasedate, i.value as itemname, sum(isnull(quantity,0)) as quantity from items i cross join ( select distinct purchasedate from purchase ) dt left outer join purchase p   on i.value = p.itemname   and dt.purchasedate = p.purchasedate group by dt.purchasedate, i.value order by dt.purchasedate, i.value 	0
13592005	6740	return all mysql records for current year	select count(*)  from table1  where year(start_date) = year(curdate()); 	0
13593484	939	select statement to output values second table if field from first and second match	select    attr_table.attr_id, attr_table.id, attr_table.value_id,    coalesce(attr_group_table.prefix, attr_table.prefix) prefix,    coalesce(attr_group_table.price, attr_table.price) price,   name_table.name from attr_table    left join attr_group_table on attr_table.attr_id=attr_group_table.attr_id   left join name_table on attr_table.value_id=name_table.id 	0
13594513	20516	how to sum each field of two columns into one column	select column1+column2 as `sum` from your_table 	0
13601071	30038	i want to display rownum along with the data in mysql by eliminating the duplicates in my table?	select @rownum:=@rownum+1 sno, a.tname from (select distinct tname from table1) a, (select @rownum:=0) r  limit 60 	0.000280882493136107
13603762	8078	create a mysql select statement combining information from shopping basket and products tables	select   b.productid,   b.quantity,   p.title,   p.description,   p.price from basket b inner join products p on b.productid = p.id; 	0.0164607940142148
13604609	30643	how to retrieve sum of data from two tables with condition	select  sum(b.fee1_fee2_totalperplayer) + sum(a.fee3) as total  from    book a join    (             select  tid,                     sum(fee1) + sum(fee2)                          as fee1_fee2_totalperplayer             from    players             group   by tid         ) b on         a.tid = b.tid where   a.reserveddate ='2012-11-25'  group by a.reserveddate 	0
13604938	12146	how i can get these from database using mysql?	select did , substring_index(pid ,'/',-1) pid from table 	0.00897052170714424
13618860	11347	can i be more specific with sql ordering?	select w.financial_year,     isnull(e.entity_name, 'entity code ' + cast(w.integer_1 as varchar) +          ' is not available on the entity table. please add.') ,     count(w.form_guid)   from portal.workflow as w      left join property.entity as e          on w.integer_1 = e.entity_id   group by case when e.entity_name is null then 0 else 1 end,         w.financial_year, w.integer_1, e.entity_name   order by case when e.entity_name is null then 0 else 1 end,        w.financial_year, e.entity_name 	0.584814142914868
13620930	29104	mysql, get last artikel in last kategori	select * from `artikel` where `idjurnal` = (select `idjurnal` from `jurnal` order by `idjurnal` desc limit 1) 	0
13623962	8543	oracle select: fastest way to get total number of rows	select *    from (select c.*, count(*) over() cnt            from (select * from table where x = 'a' etc) c           where rownum <= 2)   where cnt = 1; 	0
13625501	610	selecting joining records where all rows have a field equalling false	select * from customers where id not in (select customerid from addresses where active = -1) 	0
13629356	40912	sum grouped by multiple columns in mysql	select color, shape, material, sum( value * qt ) from tbl group by color, shape, material 	0.00234115734542428
13637439	16957	records updated during the day	select `item`.`name`,          date_sub(item.modified, interval 1 day),         case when date(item.modified) = curdate()              then 'true'              else 'false'         end status,         `item`.`restaurant_id`  from `fs_development`.`items` as `item` where `item`.`restaurant_id` = (677) order by `modified` desc limit 1 	0
13652341	4140	sql query to only retrieve records which match a list or its subset	select distinct t1.computer from table as t1 left outer join table as t2 on t1.computer = t2.computer     and t2.application not in ('microsoft office','webex','java runtime 1.6_33') where t1.application in ('microsoft office','webex','java runtime 1.6_33')   and t2.computer is null; 	0
13668023	22157	mysql join based on date range	select customercard.cardnumber, customer.firstname, customer.emailaddress, customer.lastname, cardtype, expirydate from customercard left join customer using ( emailaddress )  left join card using ( cardnumber )  where date_format( card.expirydate,  '%y-%m-%d' ) <= date_format(  current_timestamp ,  '%y-%m-%d' )  order by  `customercard`.`cardnumber` asc  limit 0 , 30 	0.000513435384356966
13671037	14420	how to filter result after a specific value	select   user_profile_data.* from     relation_table     join user_profile_data       on user_profile_data.ref_user_id = relation_table.user2 where    relation_table.type  = 1      and relation_table.user1 = 184      and user_profile_data.full_name > (        select full_name        from   user_profile_data        where  ref_user_id = 182      ) order by user_profile_data.full_name 	0.0012472694026375
13677023	1975	select multiple rows based on two or more seperate dates	select * from `users`     where date(`date`) = "2012-11-30" or date(`date`) = "2012-11-01"; 	0
13679908	25653	mysql return single row and status for multiple rows	select      o.person,     o.job,     p.risk,     case when count(c.datecompleted) > 0 then null else r.training end as training,     case when count(c.datecompleted) > 0 then 'yes' else 'no' end as trainingcompleted,     case when count(c.datecompleted) > 0 then 'good' else 'bad' end as status from orgstructure o      join personrisks p on p.person=o.person     right outer join risktraining r on r.risk=p.risk     left outer join coursescompleted c on c.course=r.training and c.person=o.person where o.department='house keeping' and o.person <> '' group by o.person order by o.person desc, case when c.datecompleted is not null then 0 else 1 end asc 	0
13685571	2195	should i check for null or dbnull in the query	select count(*) where 1=2 	0.741395842511193
13693936	40700	subquery inside if as a value for a column with null value	select if(     t1.type is null,      if(         (select t2.type from t2             where t2.table1_id=t1.id limit 1)            is not null,         t2.type,         'some defaults'),     t1.type ) as ret from t1, t2 where t1.id = t2.table1_id 	0.023755450988152
13705717	24464	check if a period is included between two dates	select  * from    mytable where   date_start between '0000-07-14' and '0000-08-25'         or date_end between '0000-07-14' and '0000-08-25'         or (date_start<'0000-07-14' and date_end>'0000-08-25') 	0.000345557245346688
13707401	1435	how to determine if a charater is uppercase or lowercase in postgresql?	select * from table      where substring(col from 1 for 1) != lower(substring(col from 1 for 1)) 	0.239127615504249
13708418	20422	totaling the number of duplicates	select sum(temp_1.count_1) as totalcount from ( select phone, count(1) as count_1 from table group by `phone` having count_1 >1) as temp_1 	0.00217836974551147
13721139	16937	mysql group_concat with distinct values from another row	select   sum(amount) totalamount,   group_concat(amount) amounts,   group_concat(doc_number) docno,   doc_date docdate,   scheme_description schemedesc from (   select scheme_description, doc_date, doc_number, sum(amount) amount     from credit_notes     group by scheme_description, doc_date, doc_number) t group by scheme_description, doc_date 	0.000312689621867117
13726077	35743	calculating percentage within the sql	select  number_of_calls, number_of_answered, ((number_of_answered/number_of_calls)*100) as answer_percent, date from table where date between '2012-09-10' and '2012-09-11' 	0.0220534161078834
13728865	7622	sqlite delete from only if the table exists	select count(*) from sqlite_master where type='table' and name='table_name'; 	0.000522336969571904
13728983	38699	mysql query link from table1 where this link hasn't exist in table2 and table3	select id, link from table1 where (link in (select link from table2)) or (link in (select link from table3)) limit 10 	0.127543282036421
13729566	9826	how to get result with variable in where condition which was set using set	select * from users where (find_in_set(id,@current)>0) 	0.0152154480197882
13741596	38582	how can i generate paginated grouped data in sql	select * from     (select row_number () over(order by t.providerid, t.rowtype )/20 as pageid ,*       from (          select * from (             select f.id, f.name, p.id as providerid, 2 as rowtype,                   'result' as rowtypetitle             from fund f             inner join provider p on f.providerid = p.id          union             select distinct f2.providerid as id, p2.name, f2.providerid, 1 as rowtype,                  'group title' as rowtypetitle            from fund f2            inner join provider p2 on f2.providerid = p2.id )y)  t           )u          order by u.providerid, u.rowtype asc 	0.0119599566503702
13744067	30106	compare mysql data within a table	select a.user_id, a.user_name, if((b.math - a.math) > 0, 'good', 'bad') math,           if((b.english - a.english) > 0, 'good', 'bad') english from (select user_id, user_name, math, english  from tbl_exam where semester = '1st') as a  inner join  (select user_id, user_name, math, english  from tbl_exam where semester = '2nd') as b on a.user_id = b.user_id 	0.00386696786868107
13749112	30669	how to select data from 2 tables by id	select p.code, s.qty from products p, stock s where p.id = s.id 	0
13764025	18206	how to match database column with string	select * from table_name where 'text1 and text2 and text3' like '%'||name||'%' 	0.0100958584275986
13774516	22741	oracle: how to put value in a variable from a sql statement	select count(*) into row_num from emp; 	0.0079942057983845
13775250	30537	sql query to get result with exclude selected id	select *  from wp_products  where product_id <>'1' and    (price<=200 or wheel_size='6'  or  studs='$studs')  order by product_id desc 	0.000524383843407098
13787176	25133	sql how to group data that matches values?	select   value,    count(*) from  smf_themes where    variable = 'invited' group by   value 	0.00246147708270089
13792327	5994	join table to subquery on another table and then sort the results	select   album_id, max(year) latest from albums inner join years on id = album_id where genre_id = 1 group by album_id order by latest desc 	0.000506418479638953
13802766	41209	using where clause when totalling entries using count() and join	select e.employee_id, count(y.employee_id) as total_holidays from employee e  left outer join holiday y on e.employee_id = y.employee_id and y.[date] between '20121201' and '20121210' where e.is_active = 'true' group by e.employee_id 	0.722962620517351
13808258	1005	join query based on date	select top 5         dc.datapointid       ,datapointdate       ,dc.datapointvalue as dvold       ,case sc.scaletype             when '*' then dc.datapointvalue * sc.scalevalue             when '/' then dc.datapointvalue / sc.scalevalue             when '+' then dc.datapointvalue + sc.scalevalue             when '-' then dc.datapointvalue - sc.scalevalue             else dc.datapointvalue         end         as datapointvalue  from tbltss_datacollection dc  left join tbltss_scalesettings sc  on sc.datapointid = dc.datapointid  and sc.effectivedate = (     select max(effectivedate)     from tbltss_scalesettings     where datapointid = dc.datapointid         and effectivedate <= dc.datapointdate  )  where dc.datapointid = 1093 	0.0107699464654711
13812856	21972	mysql finding partial duplicates	select distinct substring_index(productname,' ',1) from mobiles 	0.0160212464976874
13813121	2430	find the name of the employees, whose names are same but salary are different	select e1.e_name from employee e1, employee e2 where e1.e_name = e2.e_name and e1.salary <> e2.salary; 	0
13817950	35241	grouping and summarizing values	select distinct maker, type from product  where maker in (select maker from product                    group by maker                   having count(distinct type) = 1                      and count(distinct model) > 1) 	0.050985095733818
13824457	18420	mysql if field contains this make other field that	select        if (mt.item like '%used-%', 'used restaurant equipment', ct.tier1) as tier1,        ct.tier2    from        trx.table1 mt            left join        trx.table2 ct1 on mt.item = ct1.item            left join        trx.table3 ct on ct1.web_num = ct.webnumber    group by        if (mt.item like '%used-%', 'used restaurant equipment', ct.tier1)    limit 0 , 15 	0.00787772683114615
13848872	2294	character mask output data on select	select       substring(x.securitynumber,1,3) +       'xxxxx' +       substring(x.securitynumber,len(x.securitynumber) - 2, len(x.securitynumber))      as column1 from underlyingtable x 	0.107611889743911
13851607	20083	query to count number of different values?	select url, count(id) as countofid from (    select distinct id, url    from yourtable ) x group by url 	0.000170456571115525
13854661	1793	foreign key link referenced twice to same table in query	select msg.id, sender.id, receiver.id from message msg inner join users sender on msg.sender=sender.id  inner join users receiver on msg.receiver=receiver.id  where [put_the_where_conditions_here] order by message.timestamp desc  limit 0,10 	4.97103179931866e-05
13860499	28267	fixing large number of constraints issues reported by dbcc	select  * from    referencingtable t1 where   not exists         (         select  *         from    referencedtable t2         where   t1.foreignkeycolumn = t2.id         ) 	0.258905501350353
13863689	7739	mysql comparing the values of two columns in the same row(s) in a single table	select  * from    tablename where   not (sku like concat(`sku category`, '%')) 	0
13867560	10687	roll up daily data into monthly buckets in mysql	select year(activity_date), month(activity_date), count(*) from table group by year(activity_date), month(activity_date) 	0.000424174382766918
13875497	24231	comparison on numeric part of string in mysql	select   version      from table      having cast(reverse(if(locate(".", version), (cast(reverse(version) as decimal(4,2))), (cast(reverse(version) as unsigned integer)))) as decimal(4,2)) > 12; 	0.0535300887276717
13885261	28586	order result sets in a union	select col1, col2, col3 from ( select col1, col2, col3, 1 as sortorder from table1 union select col1, col2, col3, 2 as sortorder from table2 ) as d order by sortorder, col1 	0.175080723411953
13885579	8131	mysql - get most "liked" users in the past month	select    id_poster,    count(1) as like_count from    log_like where    time between unix_timestamp('2012-11-01') and unix_timestamp('2012-12-01') group by    id_poster order by    like_count  desc limit 10 	0
13898438	37692	sql - self join for latest row	select     a.* from     mytable a     join     (         select max(date) as `date` from mytable         where attempts in ('success', 'fail')     ) b     on a.date = b.date where     a.attempts = 'fail' 	0.0331655306826418
13900685	12839	like within query	select * from table1 where name like '_i%' 	0.757713471349716
13902941	6165	php mysql hide rows more than 1 minute old	select * from tablename where timestamp > timestamp(date_sub(now(), interval 1 minute)) 	0.00373809119348008
13914614	34072	sql query excluding specific values for the same column	select m.*  (from    milestones m inner join milesones as m1        on m1.company = m.company       and m1.project = m.project       and m1.milestone = 'milestone 1'       and m1.completion = 100) inner join milestones as m2         on m2.company = m.company                 and m2.project = m.project                 and m2.milestone = 'milestone 2'                 and m2.completion = 100 	8.63228419516543e-05
13926951	9754	select only one row matching distinct values	select id from portfolio where category = 'x' and description = 'x' limit 1; 	0
13927304	5241	merge two mysql tables and get result into datagrid in vb.net	select tblloanaccount.date, tblloanaccount.payment, tblloanaccount.interest,     tblloanaccount.total, tblloanaccount.auto, tblloanaccount.installment,          if(installment = 0, 'interest', concat('installment : ', installment)) as description from tblloanaccount  join tblloanregistry on tblloanregistry.loanid = tblloanaccount.loanid where tblloanregistry.empnumber= 1111      and tblloanaccount.loanid = 1      and tblloanaccount.total <> 0  order by tblloanaccount.id 	0.000714708108440643
13933915	37962	selecting columns randomly using mysql query	select option from tbl_answers where questionid = x order by rand() 	0.00368403653105349
13948731	27219	how can make sort by votes "by date", "by year"..?	select `id`,        sum(if(`votes`.`date` >= date_sub(curdate(), interval 2 day, `votes`.`votes`, 0)) as likes_t,         `post`.*        from `posts` join `votes` on (`id` = `votes`.`post_id`) 	0.00236633749086215
13951193	1437	select query with many to many relationship	select     m.name     , w.* from     man m          inner join manwork mw on m.id = mw.man_id          inner join work w on mw.work_id = w.work_id 	0.182135961042768
13963813	39732	mysql getting the minutes	select minute( curtime() ) 	0.00952470593001498
13972424	12891	how do you return rows from mysql based on highest value in table column?	select fieldlist from `tablename` where `score` = (select max(`score`) from `tablename`) 	0
13973144	6368	select the date from ms access in dd.mm.yyyy format	select format([date], "dd.mm.yyyy") from table1 order by [date] desc; 	0.0041218824980691
13979700	30727	sql 2 where clause	select      co,      queuedtime,      starttime,      completetime,      datediff(minute, queuedtime, completetime) as elapsedtime  from      sjob where      jobclass = 'payrollfinish' and      datediff(day,queuedtime,getdate())=0      and jobclass = 'submitpayroll' and jobclass = 'payrollfinish' order by      queuedtime 	0.597150662859594
13982183	39652	using tsql how to determine which column of a compound foreign key corresponds to which column of a compound primary/unique key?	select   fk.name as constraint_name,   sfkc.constraint_column_id,   sfkc.parent_column_id,   fkt.name as fk_table,   fkc.name as fk_column,   sfkc.referenced_column_id,   pkt.name as pk_table,   pkc.name as pk_column from sys.foreign_keys as fk join sys.foreign_key_columns as sfkc   on fk.object_id = sfkc.constraint_object_id join sys.tables as fkt   on  sfkc.parent_object_id = fkt.object_id join sys.columns as fkc   on fkt.object_id = fkc.object_id  and sfkc.parent_column_id = fkc.column_id join sys.tables as pkt   on sfkc.referenced_object_id = pkt.object_id join sys.columns as pkc   on pkt.object_id = pkc.object_id  and sfkc.referenced_column_id = pkc.column_id 	0
13984464	14422	how to combine two tables to get desired result	select  p.id,         d.device from    product p left join         device d    on  p.id = d.id 	0.000693992770134657
13987847	31076	generating number	select a,b, rank() over (partition by b order by a) c  from tbl order by a; 	0.0986336183479952
13997725	37134	mysql / wordpress meta query; combining multiple conditions	select distinct id from wp_posts, wp_postmeta  where (  wp_posts.id = wp_postmeta.post_id  and post_status = 'publish'  and post_type = 'days'  and (   wp_postmeta.meta_key = 'dates'    and wp_postmeta.meta_value >= '$startdate'    and wp_postmeta.meta_value <= '$enddate'    and wp_postmeta.meta_value != '$today'  ) ) union select distinct id from wp_posts, wp_postmeta  where (  wp_posts.id = wp_postmeta.post_id  and post_status = 'publish'  and post_type = 'days'  and (  (wp_postmeta.meta_key = '_daytype' and wp_postmeta.meta_key = 'month')  or  (wp_postmeta.meta_key = 'dates' and wp_postmeta.meta_value = '$firstdayofmonth' )  ) ) 	0.239423167083597
14000612	13424	php mysql query to get max of event id for specific user id	select  a.* from    tablename a         inner join         (             select userid, max(event_id) maxid             from tablename             group by userid         ) b on  a.userid = b.userid and                 a.event_id = b.maxid where   a.userid = 30 	0
14009372	16430	show most popular query_string	select url,         count(*) as reqs    from queries   where ts > now() - interval 24 hour   group by url   order by reqs desc 	0.0022198988713608
14020404	16784	date extraction from mysql	select asset_id from #__content where state = 1 and date(publish_up) >= date_sub(current_date, interval 7 day) 	0.0104939388725316
14043205	15836	creating a view and getting duplicate transactions	select  <yourcols> from   company.[transaction] as t  left outer join company.product as p     on t.productcode = p.productcode    and t.corporationid = p.corporationid 	0.111430255529389
14045015	8976	sql query to get the last set of distinct records with some conditions	select max(id)  from mytable where status_id != '2'      and expiry < '2012-12-26 19:00:00'      and customer_id not in (select max(customer_id) from mytable where status_id = '2' group by customer_id)  group by customer_id 	0
14055632	11693	how to show top 3 fields from a column into horizontal row in mysql?	select servicecode, ser_count, firstname, lastname, patientid,         healthcardnumber, dateofbirth, gender,         group_concat(if(auto <= 3, code, '') order by ser_count desc, servicecode separator ' ') description  from (select *, concat('(', ser_count, ')', servicecode) code,               if(@value=(@value:=patientid), @auto:=@auto+1, @auto:=1) auto       from table1, (select @auto:=1, @value:=0 ) a       order by patientid, ser_count desc, servicecode) as a  group by patientid; 	0
14059469	21560	postgres - change values before returning result set from a view	select      ('train service:'::text     ||     case tblpoi_transit_info.train_service::text         when 'y' then 'yes' else 'no'     end as train_service, 	0.00185727441921104
14065737	850	show rows data into column format	select itemname,        group_concat(case date_format(`date`,'%y-%d-%m') when '2012-01-12' then `isavailable` else null end) as `2012-01-12`       ,group_concat(case date_format(`date`,'%y-%d-%m') when '2012-02-12' then `isavailable` else null end) as `2012-02-12`       ,group_concat(case date_format(`date`,'%y-%d-%m') when '2012-03-12' then `isavailable` else null end) as `2012-03-12` from table1 group by `itemname`; 	8.08680604625007e-05
14069156	27946	individual percentage for each item, throughput	select    unitid,    count(date) * 100       / (select count(*) from items b where b.unidid = a.unitid) as percentage from items a where date !='out' group by unitid 	0
14071054	32699	group by one field and count the matching fields	select date_format(posts.postdate, '%y-%m-%d'), count(tags.tagname)     from posts     join posttags             on posts.pk_postid = posttags.fk_postid         join tags             on tags.pk_tagid = posttags.fk_tagid     where tags.tagname = 'money'     group by date_format(posts.postdate, '%y-%m-%d') 	0.00012656149670458
14080352	702	query for fetching data from multiple tables	select data you want  from first table to join  inner join secondtable  on first table userid = secondtable userid join third table  on first table userid = thirdtable userid  join fourth table  on first table userid = fourth table userid 	0.00545763379393202
14087252	30015	match the data in the database to show correct information	select * from catbreeds_personality_links as cbpl inner join catbreeds as cb on cbpl.id_breed = cb.id inner join catbreeds_personality as cbp on cbpl.id_personality = cbp.id where cbp.id = '6' order by cb.information_breed asc 	0.000636432600001741
14095220	39444	how can i combine these 2 selects into a single one?	select      @cntcm_cnf = count(distinct case when vcps.cmsuid = @nsuid then c.id_case else null end),     @cntcc_cnf = count(distinct case when vcps.casuid = @nsuid then c.id_case else null end) from dbo.cases c join dbo.vew_casepersonnelsystemids vcps on c.id_case = vcps.id_case join hearings h on c.id_case = h.id_case where      h.hearingdate > getdate()     and h.oncalendar = 1 and h.scheduled = 1     and dbo.fn_hearingconfirmednohos(h.id_hearing) < 2 and     (vcps.casuid = @nsuid or vcps.cmsuid = @nsuid)  	0.000225027080195427
14102525	4176	counting upvotes and downvotes	select cid, sum( vote) as upvoted,              sum(case                   when vote = 0 then 1                  else 0                  end) as downvoted     from yourtablename     group by cid; 	0.0957526670469718
14103001	26297	oracle get two variables returned from select query inside of a package	select myprev, mynext into prevcontentid, nextcontentid from mytable where contentid = thecontentid; 	0.00280910458837095
14106957	13319	mysql union multiple tables into one large table	select 'a' as table_name, id, name from table_a union all select 'b' as table_name, id, name from table_b 	0.00215516968412061
14112541	8209	how to retrieve the published post in wordpress database?	select * from wp_posts where post_status = 'publish' and post_type = 'post' 	0.000285994211772689
14114432	3574	exclude mysql table records that have matching, newer records	select prism_actions.* from prism_actions join (     select x, y, z, max(action_time) as action_time     from prism_actions     group by x, y, z) latest   on prism_actions.action_time = latest.action_time   and prism_actions.x = latest.x   and prism_actions.y = latest.y   and prism_actions.z = latest.z where prism_actions.world = 'world' and (prism_actions.action_type = 'block-place') and (prism_actions.player = 'viveleroi') and (prism_actions.x between -448.7667627678472 and -438.7667627678472) and (prism_actions.y between 62.0 and 72.0) and (prism_actions.z between -291.17236958025796 and -281.17236958025796) order by x,y,z asc limit 0,1000000 	0
14126007	24014	find all rows with no matching result sql	select * from employees where still_working_for_company and not exists (   select true   from tasks   where tasks.firstname = employees.firstname   and tasks.lastname = employees.lastname ) 	6.76755971016987e-05
14131253	17839	collective maximum	select     mgr.id,     mgr.name,     sum(awd.points) as totalstaffpoints from    employee as mgr join    employee as stf on mgr.id = stf.manager_id join    awards   as awd on stf.id = awd.employee_id group by mgr.id, mgr.name order by totalstaffpoints desc 	0.0302272997140785
14158948	34068	counting events by unique id	select chore, count(distinct day_id) cnt from chores where chore='washed the dishes'  group by chore 	0.000282723929401396
14164565	36142	given a trigger in postgresql how to determine it's relationship	select tgname,relname from pg_trigger join pg_class c on tgrelid=c.oid; 	0.00307055707182267
14178814	5635	mysql search x amount of rows for specific terms	select t.`rating_score` from (select *       from archived_videos       order by `rating_score` desc       limit 0,21) t where t.search_terms='banned commercials' 	6.40005423956928e-05
14193407	26867	sql server get min time?	select [username], [date] , min(case when [action] = 'clock in' then [time]  end) as 'first in' , min(case when [action] = 'clock out' then [time] end )as 'first out' , max(case when [action] = 'clock in' then [time] end) as 'last in' , max(case when [action] = 'clock out' then [time] end )as 'last out' from attendance where [username] = 'user1' and [date] = '01/12/2012' group by [username],[date] 	0.0253131350444767
14193848	9094	selecting the most recently added record to the database in mysql	select * from table_name order by id desc,limit 2. 	0
14223148	22145	how do i get the error description from an error code in sql?	select @errorvariable as errorid,     text from sys.messages where message_id = @errorvariable; 	0.635015045316253
14225811	24707	how to sum mysql rows	select sum(`contract_fine`) as totalfine from `contract`  natural join `rented_vehicle` where `contractid` = 3; 	0.01152617250714
14241780	10037	select col1, col2, col3 from table where column1 has duplicates	select col1, col2, col3 from t5 where col1 in (     select col1     from t5     group by col1     having count(col1)>=2 ) 	0.00695498488658083
14243978	16242	mysql xref tables	select p.* from products p left join categry_prod cp on cp.prod_id=p.id where cp.cat_id=1; 	0.189969593963275
14256306	17407	check datetime field before insert	select max(`mydate`) as mydate from `tablename`; or select `mydate` from `tablename` order by `mydate` desc limit 1; or if you have a primary key auto-increment column called id this may be fastest: select `mydate` from `tablename` order by `id` desc limit 1; <?php $last_insert_time = strtotime(); # use the result from the database query as the parameter $now = time(); # if the difference between the last inserted entry and the current time is less # than five seconds perform an error action. if (($now - $last_insert_time) < 5) {     $error = 'please wait 5 seconds before insert'; } 	0.0064875894130577
14273623	38271	sql columns multiplication error	select            itemno ,                   name ,                   category ,                   rate ,                   quantity,                   rate*quantity as total from test 	0.689618106153674
14274548	10478	sql sampling of quantum values	select (floor(p.sum / 50) + 1) * 50 payment, count(*) num_users  from payments p group by floor(p.sum/50); 	0.0264635784516358
14274702	38150	join tables with one known variable in second table	select  *   from  a inner join b on a.t_id=b.id where  a.type='loading' and b.shipid=2 	0.000360205733919769
14285777	3748	trouble with join statement for selecting data across tables with mysql	select events.*, registration_items.*, registration_signup.*, users.username from events   inner join users on users.userid = events.userid   left join registration_items on registration_items.event_id = events.event_id   left join registration_signup on registration_signup.id = registration_items.id where registration_signup.userid = '$user_id' union select events.*, registration_items.*, registration_signup.*, users.username from events   inner join users on users.userid = events.userid   inner join registration_items on registration_items.event_id = events.event_id   inner join registration_signup on registration_signup.id = registration_items.id where events.userid = '$user_id' order by events.event_timestamp desc 	0.368705066059915
14289760	31524	mysql pivot table: how to get row and column totals and add a conditional column?	select t.*,        ("1d:currency:50" + "2b:currency:50" + "brg:currency:50" + "bht:currency:50"        ) as tot1,        (case when "1d:currency:50" + "2b:currency:50" < "so:currency:50"              then '1 cord'              when ("1d:currency:50" + "2b:currency:50" + "brg:currency:50" + "bht:currency:50" < "so:currency:50" + "rol:currency:50"              then  "2 cstk"          end) from (<your query>) t 	7.08840893390465e-05
14290540	25843	#1248 - every derived table must have its own alias	select *  from t_inv_dtl t   left join ( select inv_dtl_id , group_concat( distinct employee_id ) as employee_id              from t_inv_investigator              group by inv_dtl_id ) a on t.inv_dtl_id = a.inv_dtl_id  join t_investigation ti on t.inv_id = ti.inv_id 	0.0136128713999038
14291464	39424	subtracting the results of two queries	select r.room_name, count(k.key_id) as key_count from rooms as r inner join keys as k on r.room_id = k.room_id  where k.key_id not in (     select k2.key_id     from keys as k2     inner join signin as s on k2.key_id = s.key_id     where s.[return_date] is null) group by r.room_name order by 2 desc 	0.00140132687572362
14305215	2866	show results with biggest count mysql	select username,email,count(*) as cnt  from users, comments  where author = username   group by username  order by cnt desc  limit 1 	0.0129587920173864
14306014	36766	mysql query must also show posts without votes	select all               upload.*,               count(ifnull(ratings.id,0)) as totalrates,               avg(ifnull(ratings.rating,0)) as avgrating,               users.nickname             from               upload inner join               users on upload.users_id = users.id left join               ratings on ratings.upload_id1 = upload.id             group by               upload.id desc 	0.000808520950999532
14310571	5291	sql hide result if all three fields are 'yes'	select *  from yourtablename  where planchanged is null or planchanged <> 'yes'  or dataremoved is null or dataremoved <> 'yes'  or rolloverenabled is null or rolloverenabled <> 'yes' 	0.00113680300783769
14322616	26919	counting a specific row in table	select * from requests where rq_poster = '$rq_notice_user' and rq_stamp > 0 	0.000408896312560633
14323688	21324	mysql function using regexp capturing and returning the second, third, and forth characters in string	select my_table.* from my_table join (   select   left(company_name, 4) as abbr   from     my_table   group by abbr   having   count(*) > 1 ) t on left(my_table.company_name, 4) = t.abbr order by my_table.company_name 	0.0920550113594657
14332192	5839	post gre: natural full join- how to replace null values in the int column with zeros?	select (...), coalesce(intcolumn,0) from (...) 	0.018770996253587
14352523	706	join two tables having different number of columns	select   t1.businessid,   t1.userid,   t1.name,   t2.systemid from   table1 t1 cross join   table2 t2 ; 	0
14367174	6769	how can i group by time in sql	select    [date] = convert(date, logdate),    [sum] = count(*) from dbo.log_table_name where [type] = 'dberror' group by convert(date, logdate) order by [date]; 	0.171204241579605
14378822	9765	how to get mmm dd yyyy hh:mm:ss format in sql server 2008	select convert(varchar(12), sysdatetime(), 107) +' '+ convert(varchar(12), sysdatetime(), 108) as [mon dd, yyyy] 	0.00932078217386036
14385788	13873	sql order by count specific strings	select *,(length(`your_field`) - length(replace(`your_field`, "w", ""))) as `letter_count` from `your_table` where 1 order by `letter_count` desc 	0.0454852149793246
14386904	35800	select last 250 rows from a table with no auto id	select col1, col2, ...  from (select col1,col2, ..., (@auto:=@auto+1) indx        from tablename, (select @auto:=1) as a      ) as b  order by indx desc  limit 30 	0
14391849	10755	need count from a more complex query	select count(*) as totalcount from ( select a.[queueid] from couponqueue a join coupon b     on a.couponid = b.couponid join listing c     on b.listingid = c.listingid where (a.[user_id] = @passeduserid) and (b.[couponactive] = 1) and (b.[isdeleted] = 0) and (b.[couponexpire] > dateadd(dd, -1, getdate()) or b.[couponexpire] is null) ) t 	0.607422089480903
14395338	91	how do i right outer join to contain multiple columns?	select      b.date,      a.a,      a.b,      case        when a.date = b.date then a.value        else 0      end as value from #temp a  cross join #calendar b 	0.703353232601377
14395865	11807	highest interval between two dates same table	select     sentdate, lag(sentdate) over(order by sentdate) previous_sentdate,     sentdate::date - lag(sentdate) over(order by sentdate) days from t order by sentdate 	0
14404096	33818	month grouping - get count for each month	select   m.mo,   count(t.dateentered) from (     select '01' as mo from dual union all     select '02' from dual union all     select '03' from dual union all     select '04' from dual union all     select '05' from dual union all     select '06' from dual union all     select '07' from dual union all     select '08' from dual union all     select '09' from dual union all     select '10' from dual union all     select '11' from dual union all     select '12' from dual   ) m     left outer join   mydatatable t     on       m.mo = to_char(t.dateentered, 'mm') and        t.dateentered >= date'2011-01-01' and       t.dateentered < date'2012-01-01' group by   m.mo order by   m.mo 	0
14407174	16762	find column name sql	select v.*,        (case when v.id = n.ch1 then 'ch1'              when v.id = n.ch2 then 'ch2'              when v.id = n.ch3 then 'ch3'         end) as whichcolumn from variables v join      names n      on v.id  in (n.ch1, n.ch2, n.ch3) 	0.00809966237560763
14410392	26686	thinking about a way to organize database	select article_id, count(article_id)      from yourtable      group by article_id 	0.576816594017591
14414616	27861	get number of rows of the sum of two columns and group these rows	select      *, count_t1 + count_t2 as count_all from     (select d_id, count(content) as count_t1 from tablea group by d_id) t1     left join     (select d_id, count(dif_content) as count_t2 from tableb group by d_id) t2     on t1.d_id = t2.d_id; 	0
14416593	2898	nontrivial query	select ... from main_table left outer join join_table1 j1 on ... left outer join join_table2 j2 on ... order by coalesce( j1.id, j2.id ) 	0.46185082725027
14416789	2400	mysql query check if user like	select      p.post_id,     p.title,     if(l.post_id is not null,1,0) as like from posts as p left join likes as l on l.post_id = p.post_id and l.userid = p.userid where p.userid = 1 	0.309242518035108
14435318	17738	display order of the string to the data stored in the database	select i.id_item_order, i.id_order,         o.no_order || chr(rownum + 64) as no_order from item_order i inner join "order" o on o.id_order = i.id_order; 	6.46231067918909e-05
14439378	30005	select rows from sql table and 5 rows from another	select   *   from ls_categories c  inner join (     select       *, row_number() over(partition by catid                           order by item_id asc) rownum    from ls_itemtypes ) l  on c.catid = l.catid     and l.rownum <= 5 inner join ls_files f on l.item_id = f.id where c.nodeid = 183; 	0
14440818	33904	"explode" table returned by sql function into columns	select name, (symbol_scan(id)).*  from symbols 	0.0212135114137083
14447135	12886	sql query - how to show when data repeats itself for x number of entries	select             sites.site_name,             measurements.measurement_name,             trend_data_temp.trend_data_avg,             [occurances] = count(trend_data_temp.trend_data_time)      from   sites             inner join group_sites                     on sites.site_id = group_sites.site_id             inner join groups                     on group_sites.group_id = groups.group_id             inner join measurements                     on sites.site_id = measurements.site_id             inner join trend_data                     on measurements.measurement_id = trend_data.measurement_id             inner join trend_data_temp                     on measurements.measurement_id = trend_data_temp.measurement_id      group  by             sites.site_name,             measurements.measurement_name,             trend_data_temp.trend_data_avg     having count(trend_data_temp.trend_data_time) >=48 	0
14465008	7827	using limit and join	select b.name,        a.name from bands b join albums a on a.id_band = b.id_band where b.id_band = (select max(id_band)                    from bands) 	0.648289799073914
14471179	5724	find duplicate rows with postgresql	select * from (   select id,   row_number() over(partition by merchant_id, url order by id asc) as row   from photos ) dups where  dups.row > 1 	0.00194908489702895
14479526	1283	sql group by clause with two columns	select row_number() over(order by column_name) as id, column_name from (       select distinct column_name from tblname    ) as a 	0.100594341682146
14482208	6620	group records by users mysql/php	select  a.* from    messages a         inner join         (             select  sender, max(id) max_id             from    messages             group   by sender         ) b on a.sender = b.sender and                 a.id = b.max_id 	0.0104030680365546
14485308	36790	converting time formats from sas to sql (converting time elapsed to date)	select    timestamp with time zone 'epoch' + interval '1 second' *       cast((cast(time_var as bigint) / 1000) as integer) as postgres_timestamp,    date(timestamp with time zone 'epoch' + interval '1 second' *       cast((cast(time_var as bigint) / 1000) as integer)) as postgres_date 	0.0258887019882887
14492314	2961	mysql selecting greatest difference between 2 rows within the past day	select       pregroupbyname.`name`,       pregroupbyname.maxc1 - pregroupbyname.minc1 as maxspread    from       ( select                t1.`name`,               min( t1.c1 ) as minc1,               max( t1.c1 ) as maxc1            from               table_a t1            where               t1.`time` between '2013-01-01' and '2013-01-17'              group by               t1.`name` ) as pregroupbyname    order by       maxspread desc    limit 1 	0
14507005	35049	how can i order a selection by the results of a function (sum)?	select bill_no, bill_month, ..., (consumption + consumption2 + consumption3) as tot_sum   from ws_bill  order by tot_sum desc 	0.0590996081855072
14511536	541	how to get value from a table base on "prefrence"	select     id ,   max(alphabet) as preference from     t1 group by     id 	0
14513105	7065	sql select query merged with a computation statement	select left (convert(nvarchar,e.account) ,5)+'-'+ convert(nvarchar, ( 50 +((e.account)%10) -((e.account/10)%10) +((e.account/100)%10) -((e.account/1000)%10) +((e.account/10000)%10) -((e.account/100000)%10) +((e.account/1000000)%10) -((e.account/10000000)%10) +((e.account/100000000)%10))%10 ) +right(convert(nvarchar,e.account),4) as 'account',  e.accountname,  e.computername,  e.regloginid,  e.email,  e.telephone,  e.community,  e.status,  cast(cast(e.startdate as float) as datetime) as 'start-date',   cast(cast(e.lastbackupdate as float) as datetime) as 'lastbackup-date',  e.totalfilesize,  e.totalfilecount  from expandedcustomerview e where e.status = 'a' and e.regloginid = @0 	0.630378101308477
14522702	29059	sql limit query	select top 25 im1.*  from images im1  left join ( select top 40 id from images order by id ) im2 on im1.id = im2.id where im2.id is null order by im1.id 	0.607968628873785
14529176	8166	get original values with average from t-sql pivot using cte	select readingdate, min(readingvalue), max(readingvalue),  avg(readingvalue) from fac_weeklyreadings  wr  join  fac_weeklyreadingshistory h     on  h.weeklyreadingid =  wr.weeklyreadingid                  where wr.weeklyreadingid in (149,150)    and h.readingdate between '1-1-2012' and '12-31-2012' group by h.readingdate 	0.000865529535466175
14531763	19393	mysql virtual column in where	select a.`last` from   (select from_unixtime(`lastlogin`) as `last`          from   `players`          where  `lastlogin` <> 0) a  where  a.`last` < '2012-10-01 00:00:00'; 	0.0787598508502222
14535508	13165	selecting all the from a table in a column	select convert(uniqueidentifier,        stuff('62799568-6ef2-4c95-84e7-4953a6959c99',1,len(rn),convert(varchar,rn))) id,        t.eventid,         t.eventtitle ,         t.eventnote from      (          select  x.eventid,                  x.eventtitle ,                  x.eventnote,                  row_number() over (order by x.eventid) rn         from    dbo.asfc_app_timetable as x      ) t 	0
14573863	15717	group by questions	select           [user_id] from             [user_question_answers] a group by         a.[user_id] having           max(case when a.[answer_id] in (6,9) then 1 else 0 end) = 1 and              max(case when a.[answer_id] in (1,10) then 1 else 0 end) = 1 	0.336130972448193
14583803	26871	php times out and phpmyadmin crashes on query with not in	select      gebruikers.g_id from     gebruikers         left join     objecten on objecten.o_g_id = gebruikers.g_id where     objecten.o_g_id is null         and o_startdatum <= now()         and o_startdatum >= (now() - interval 5 day); 	0.739356740009054
14588339	22262	sql split column data	select substr(name, 1, instr(name, ' ')) as firstname,    substr(name, instr(name, ' ')) as lastname from displayname 	0.0120195236340252
14588751	32408	calculating horizontal totals in pivot in ms sql server 2008	select case when grouping([fcode]) = 1 then 'total' else [fcode] end as [fcode],        sum([dmar15]) as dmar15,        sum([dmar02]) as [dmar02] from   (select [fcode],                [aggregate],                [qname]         from   [tblmiquestresults]) as sourcetable  pivot (avg (aggregate) for [qname] in ([dmar15], [dmar02], [dmar13],                                         [dmar06], [pcvdr41], [pcvdr42],                                         [cldp031], [cldp003], [cldp012],                                         [cldp028], [cldp023], [cldp021],                                         [cldp016], [cldp022])) as p  group by grouping sets ((fcode),()) 	0.62575479288356
14606237	1221	php script passing whole object from class to class	select [fields] from records order by created desc limit 1 	0.331618919289908
14615171	20821	calculating last login time from database mysql	select timestampdiff(hour,lastlogintime,now()) from mylogintable 	7.83503691752585e-05
14621542	32826	checking mysql database for duplicate entry	select     t.billing_id, t.user_id from     (     select         billing_id, game_id, count(*)     from         tc_services     group by         billing_id, game_id     having         count(*) > 1     ) x     join     tc_services t on x.billing_id = t.billing_id and x.game_id = t.game_id 	0.00308540852828762
14634972	26059	nested sql server query max date	select      *  from      view c      inner join      (          select              category,              max(uploaddate) as maxuploaddate           from              view          group by              category     ) temp on temp.category = c.category and uploaddate = temp.maxuploaddate 	0.615356006461731
14649478	28174	mysql: counting null values from a query	select *, ((col1 is null) + (col2 is null) + (col3 is null)...) as sum_null from table where id = 1 	0.00524291612863031
14661446	27056	get last 5 rows but in order created	select * from   table where  mesid in (select top 5 mesid                  from   table                  where touser like '%krissy%' or fromuser like '%krissy%'                    order by                         mesid desc) order by        mesid asc 	0
14672657	12818	how to select the 3rd row from a table in mysql?	select * from (    select *    from emps    order by empid    limit 3 ) as t order by empid desc limit 1 	7.21985595299876e-05
14681850	4951	an efficient way to write mysql query that has duplicate column names	select post.post_id, comment.post_id as comment_post_id, * from ... 	0.0051312274774088
14693297	40465	mysql select priority - select one row or another (select a default or "fallback" row)	select * from international where script = 'generic' and lang = case   when exists(     select 1     from   international     where  script = 'generic'        and lang   = 'nl_nl'     limit  1   ) then 'nl_nl'   else 'en' end 	5.52812322681837e-05
14700984	12614	how to count a row in group but one number one time php mysql	select tmp.brand, count(tmp.shcode) as shops from (                                            select distinct temp.brand, (select distinct temp.shcode) as shcode from (select p.brand, s.shcode                                                                 from product p                                                                  inner join sdetail s on s.pcode = p.pcode) as temp                                           ) as tmp group by tmp.brand 	0
14710243	26938	how to find periods without activity in bigquery	select   utc_usec_to_hour(parse_utc_usec(timestamp_usec)) as hour_bucket,   count(*) as activity_count group by   hour_bucket order by   activity_count asc; 	0.0464560934134908
14710538	14349	select most early comming employees	select  e.hiredate  as loc,d.loc  as comdate  from    scott.emp e, scott.dept  d  where e.deptno= d.deptno   and e.hiredate in (      select  min(e.hiredate)        from  scott.emp e       group by d.loc    )   / 	0.00267810917529566
14736140	23347	mysql find friends of player x from table games	select b.id_player, b.id_game  from players a,       players b  where a.id_player = '55'  and   b.id_game   = a.id_game  and   b.id_player <> '55'  and   a.id_game > 2 order by b.id_game limit 2; 	0
14742940	28098	mysql - can i combine many queries on the same table into 1 query?	select sum(case when inventory <= 5 and cat_id = 1 then 1 else 0 end) q1result,    sum(case when inventory between 5 and 10 and cat_id = 1 then 1 else 0 end) q2result,    sum(case when  inventory > 10 then 1 else 0 end) q3result from products 	0.000240308106141258
14755134	14037	how do i use joins in a merge into statement?	select * into #temp from sys.objects go ;with cte as (     select t1.*     from #temp t1     join #temp t2 on t1.object_id = t2.object_id ) merge cte using (     select 1 as [month_id], 1 as [member_id] union all     select 2 as [month_id], 3 as [member_id] union all     select 4 as [month_id], 4 as [member_id] ) as u on cte.object_id = u.[month_id] when matched then delete; 	0.365672966145817
14762313	10281	how to perform case on values from subquery	select a.[column1], b.[column1],        (case when a.col_2_3 >= b.col_2_3 then a.col_2_3              else b.col_2_3         end) from (select a.*,  (a.[column2] + a.[column3]) as col_2_3       from [table_a] a      ) a inner join      (select b.*, (b.[column2] + b.[column3]) as col_2_3       from [table_b] b      )b      on a.id = b.id 	0.228484112334883
14770863	39674	select n:n relationship in one row with oracle (to create an view)	select   u.name,       (select      (rtrim(xmlagg(xmlelement(x, applications.application||',')order by applications.application).extract('     from         has_applications             left join applications on has_applications.user_id = applications.id     where         has_applications.user_id = u.id)           from    users u 	0.00709282690419605
14773557	5179	mysql - using sum with join	select groups.id,groups.name,users.name,sum(content.duration) as duration from groups    join users on groups.owner=users.id    join items on items.group=groups.id    join content on content.id=items.content    group by groups.name 	0.62583120919925
14775021	36654	get references without subquery	select distinct p.num,    max(pr.refnumber) over (partition by p.num order by creationdate desc)  as refnumbertokeep from part p   inner join partref pr on pr.refnumber = p.id 	0.0654719415384271
14787890	12055	sql - find the grade of students who only like students in the same grade	select * from highschooler h where not exists (select 1 from highschooler h2 where h2.grade != h.grade and exists (select 1 from friends f where (f.id1 = h.id or f.id2 = h.id) and (f.id1 = h2.id or f.id2 = h2.id))) order by grade, name 	0
14805179	19162	alter table using sub select	select concat('alter table `field_data` ',    group_concat(' change column `field_id_', field_id, '` ',     ' `field_id_', field_id, '` decimal not null'))  from `field_info`  where `field_type` = 'a_decimal_field' into @sql; prepare stmt from @sql; execute stmt; 	0.225696502295616
14805811	31201	oracle sql select distinct	select * from [table_1] where  [id] in (select min([id]) from [table_1] group by  code) 	0.258872831957865
14806271	10655	ordering sql results by the field where they are found	select * from atable where name        like '%string%'    or description like '%string%'    or type        like '%string%' order by    case      when name        like '%string%' then 1      when description like '%string%' then 2      when type        like '%string%' then 3    end ; 	0.00360337669689794
14816299	22598	query for selecting based on multiple date columns and ordering results	select id, courseid, date1 date from yourtable where date1>'0000-00-00' and date1<=curdate() union select id, courseid, date2 date from yourtable where date2>'0000-00-00' and date2<=curdate() union select id, courseid, date3 date from yourtable where date3>'0000-00-00' and date3<=curdate() union select id, courseid, date4 date from yourtable where date4>'0000-00-00' and date4<=curdate() order by date 	0
14822416	32283	count by range only returns one row	select case         when (poll_propensity >= 1 and perm_absentee = 'n' and mail_propensity = 0)     then '100%'          when (poll_propensity >= 0.90 and perm_absentee = 'n' and mail_propensity = 0)  then '< 90%'         when (poll_propensity >= 0.80 and perm_absentee = 'n' and mail_propensity = 0)  then '< 80%'          when (poll_propensity >= 0.70 and perm_absentee = 'n' and mail_propensity = 0)  then '< 70%'         end as row,             'voters' as col, count(voter_id) as data, 8 as seq from (  select p.voter_id, p.perm_absentee, vp.poll_propensity, vp.mail_propensity          from voterprofile p              inner join districtprecinct d on d.precinct_id=p.precinct_code               inner join voterpropensity vp on p.voter_id=vp.voter_id                 where d.district_id= 3 and vp.election_type= 't' ) as derived  group by row 	4.99663145173167e-05
14829834	36035	different ways to perform this query?	select e.event_id, t.* from events e left join tasks t on e.event_id=t.relatedgateid where e.event_isphase = 1 or t.relatedgateid is not null 	0.75450256208236
14839006	36008	assign the dynamic url to the variable	select @variablename = 'http:   + convert(varchar,@someothervar or column_name) + '&abc=1' 	0.0580072209506678
14846543	5093	mysql select query search one word in multiple columns	select * from property where posthead = $search or requestto = $search ... 	0.00399909182081843
14849304	19108	join two tables date from first in range of dates from second	select eh.*, eo.overtime_date  from employee_holidays eh join employee_overtimes eo on (eo.employee_id = eh.employee_id) and     (eo.overtime_date between eh.start_date and eh.end_date) 	0
14878604	21395	breaking down data into groups	select     top (100) percent dbo.census.group_code, dbo.census.gender, sum(dbo.v_courses.dur_in_hours)                    as sumof_dur_in_hours from         dbo.v_courses  inner join dbo.census     on dbo.v_courses.job_group_code = dbo.census.group_code    and dbo.v_courses.gender = dbo.census.gender where     (dbo.v_courses.system = 'gems') and (not (dbo.v_courses.course_id like 'ups%')) and                    (dbo.v_courses.first_access_date between convert(datetime, '2012-01-01 00:00:00', 102) and convert(datetime, '2012-12-31 00:00:00',                    102)) group by dbo.census.group_code, dbo.census.gender order by dbo.census.group_code 	0.00775418881545159
14883417	14762	sql order by a calculation of two columns in a table	select col1, col2, (col1/col2)*100 as total   from your table order by 3 desc / 	0.000811745420203813
14894735	35711	finding mutual friends list	select     * from (     select         case when t2.user1=1 then t2.user2 else t2.user1 end as userid     from         t as t2     where 1 in (t2.user1,t2.user2)     and t2.[status]=1 ) as tbl where exists  (     select         null     from         t     where 2 in (t.user1,t.user2)     and tbl.userid=(case when t.user1=2 then t.user2 else t.user1 end)     and t.[status]=1 ) 	0.00115496247675877
14895798	34052	limit results in sql query mysql	select id,    name,    date_created,    department from (     select @currow:=case when @prevrow = department then @currow+1 else 1 end as rn,       id,        name,        date_created,        department,       @prevrow:=department   clset     from yourtable       join (select @currow:= 0) r     order by department, date_created desc   ) t where rn <= 2 	0.584409065314909
14895910	31968	get latest date before date value in row	select  p.id,          p.patient,         p.proceduretype,         p.proceduredate,         [lastexamdate] = exam.proceduredate,          [dayssincelastexam] = datediff(day, exam.proceduredate, p.proceduredate),         [lastexamtype] = exam.proceduretype  from    procedures p         outer apply         (   select  top 1 exams.proceduretype, exams.proceduredate             from    procedures exams             where   exams.proceduretype like '%exam%'             and     exams.patient = p.patient             and     exams.proceduredate <= p.proceduredate             order by exams.proceduredate desc         ) exam; 	0
14897714	31816	how to select max value on second primary key	select a.id, a.version, a.name from table1 a inner join ( select id, max(version) version from table1 group by id ) b using(id, version) 	0
14902580	18919	selecting non-group field from query with aggregate function	select id, tbl.dateof dateof from tbl  inner join  (select fk, max(dateof) dateof    from tbl    group by fk) temp on tbl.fk = temp.fk and tbl.dateof = temp.dateof 	0.119028625320894
14902583	38532	ssms - pivoting a column and changing the field names	select [period],     [a_1_a_gross_written_premium] as [gross written premium],     [a_net_earned_premium] as [net earned premium],     [a_1_gross_earned_premium] as [gross earned premium] from   (    select [statement_line], [period], [output_ytdincstmt]    from table1    ) as source pivot   (    max(output_ytdincstmt)    for statement_line in ([a_1_a_gross_written_premium], [a_net_earned_premium], [a_1_gross_earned_premium])   ) as pivottable 	0.000729422251894214
14909897	13630	mysql : how to split text and number with "-"	select case when floor(substr(name, 3,1)) > 0 then concat_ws('-', substring(name, 1, 2), substring(name, 3, length(name))) else concat_ws('-', substring(name, 1, 3), substring(name, 4, length(name))) end as new_name from test 	0.0319506262293558
14911245	6280	top records with sub top records sql	select top 50 * from sample_table where name = 'house' union all select top 50 * from sample_table where name = 'plane' 	0.00102143935209452
14913385	5243	how to order comments by likes/dislikes in mysql	select c.content,      sum(case when r.rating = 'l' then 1 else -1 end) as overallrating from content c left join ratings r on r.id = c.id group by c.content order by overallrating 	0.05750068436871
14922218	9895	multiple rows in single column	select  a."property_id",         array_agg(b."first_name" || ' ' || b."last_name") as "claimers" from    property a         inner join claimers b             on a."property_id" = b."property_id" group by a."property_id" 	0.00139611509523707
14926792	9303	duplicate content in left join query + get count on joined table	select     t.`id`,     t.`post`,     t.`desc`,     t.`date`,     count(l.`like`) as `likecount`,     count(l.`dislike`) as `dislikecount` from `test` t     left join `likes_dislikes` l        on t.`id` = l.`song_id` group by t.`id`, t.`post`, t.`desc`, t.`date` order by t.`id` desc; 	0.00178938167113365
14940228	27843	mysql single insert using subquery rows as columns	select u.id as user_id, sub1.aid, sub1.bid, sub1.cid from user u,  (select a.id as aid, b.id as bid, c.id as cid from question a, question b, question c where a.category = :category and a.category = :category and a.category = :category and a.id != b.id and a.id != c.id and b.id != c.id order by rand() limit 1) sub1 where u.id =:uid 	0.00578117774009123
14942182	19721	how to get a certain value from an associative table in sql	select a.name, b.name, ab.date from a join ab on a.pk=ab.pk join b on ab.id=b.id where a.pk=value 	0
14969067	25253	getting the ceil value of a number in sqlite	select (case when x = cast(x as int) then cast(x as int)              else 1 + cast(x as int)         end) 	0.000227619665618387
14971875	8161	sql: how to select where date field is specific month?	select     id from     invoices where     entry_datetime > '2012/12/31' and entry_datetime < '2013/02/01' 	0.000223302762926243
14974006	25294	how to get counts in mysql left join?	select  d.name,          count(e.id) totalemployeecount from    department as d          left join employee as e              on e.depid = d.id group   by d.id; 	0.12125922491989
14986457	12360	counting records issue	select businesscatid ,count(businesscatid) as nummembers_in_cat     from memberbusinesscats     group by businesscatid 	0.151379386999784
14995650	13929	is there a oracle hint to execute the where clauses in a specific order?	select        *    from table    where datecolumn > sysdate - 5 and datecolumn < sysdate - 1; 	0.651969583163425
15004353	10479	sql joins and group by with 3 separate tables	select distinct items.[item description],         itemquantities.[qty available],        items.[selling u of m],         items.[item number],         v.vname from itemquantities     inner join items on itemquantities.[item number] = items.[item number]     inner join vendors on         right(items.[item number], 3) = left(vendors.[vendor id], 3) where items.[item number] like 'wh%'        and items.[item number] not like '%rmw' 	0.150902984139991
15005686	21446	generate a 5 digit number, but with exception from a mysql table column	select anumber from ( select lpad(convert(a.i+b.i*10+c.i*100+d.i*1000+e.i*10000,char(5)),5,'0') as anumber from integers a, integers b, integers c, integers d, integers e) sub1 left outer join images b on sub1.anumber = b.file_name where b.file_name is null order by rand() limit 1 	6.27393288493202e-05
15023095	33070	how to display right result	select t.line, min(t.start), max(t.end), t.typ, t.color from dbo.tablename t group by t.line, t.typ,  t.color 	0.0396524812095009
15027962	20140	sql can you put an if statement in a select procedure?	select distinct *  from mytable where    (@name is null or @name = name)    and     (       (@flag = 'c' and (@lname is null or @lname = 'doe'))       or        (@flag != 'c' and (@lname is null or @lname = lname))    ) 	0.457104547770271
15039128	3629	mysql | how to get latest articles from each category?	select id as postid,        post_title as posttitle,        meta_value as categoryid,        name as categoryname,        post_date as `date`   from (select *           from wp_posts as p                inner join wp_postmeta as m                   on p.id = m.post_id                inner join wp_terms as t                   on m.meta_value = t.term_id          where m.meta_key = 'matchdayteamscategory'         order by p.post_date desc) tmpview group by categoryname; 	0
15042054	27517	query to find mutual likes?	select p.p1, p.p2 from likes p     inner join likes p2 on          p.p1=p2.p2 and          p.p2=p2.p1 and          p.p1<p2.p1 	0.0219581059717395
15051449	32994	how to get maximum count of a field in a table in tsql and groupby	select top 1 tfenterancedate, count(tfenterancedate) as enterance from customer_complex_loginlogs  group by tfenterancedate order by count(tfenterancedate) desc 	0
15055540	37838	mysql create freqency distribution	select     floor( birds.bird_count / stat.diff ) * stat.diff as range_start,      (floor( birds.bird_count / stat.diff ) +1) * stat.diff -1 as range_end,      count( birds.bird_count ) as times_seen from birds_table birds,      (select          round((max( bird_count ) - min( bird_count ))/10) as diff     from birds_table     ) as stat group by floor( birds.bird_count / stat.diff ) 	0.171786907942413
15066749	31640	linking mysql tables	select     org.orgname,     dep.depname from     organization_dep dep     inner join organization org         on dep.orgid = org.id 	0.034585762917309
15066988	12802	postgressql don't filter if results empty	select * from users where     country = sp     or not exists (select 1 from users where country = sp) 	0.0802541419194677
15080915	6015	get date range from mysql database	select min(date_column), max(date_column) from your_table 	8.700620809589e-05
15094348	39041	extracting data from a very old unix machine	select into 	0.00414281385338487
15126399	9441	searching in sql based on values in 2 columns	select * from your_table where column1 not in (     select column1     from your_table     where column2 = 'p4' ) 	4.88089005410805e-05
15146468	13247	showing rollup in last line only	select * from  (   ...your query above... ) as x where register <> '[register]'; 	0.00109338576898899
15154527	41196	getting records from sql table by checking multiple columns	select t1.id from table t1 where exists (               select *               from table t2               where t2.defid = 1 and t2.valstr = 'hi'               ) and  t1.valint = 1 	5.40024472085277e-05
15201518	29348	sql subquery: filter entries that return no rows	select job_id  from paper1  where job_id not in (select job_id from paper2 group by paper2) group by job_id; 	0.00026217559857897
15202420	16608	oracle sql percentages in a single query	select 100 * sum( case when (maint_fault_date + 5) < maint_action_date                    then 1                    else 0 end        ) / count(*) as percentage from mainthistory; 	0.784852623336079
15204333	20724	mysql query to ungroup data	select id, name  from t join        (select d1.d + 10 * d2.d + 100*d3.d as num         from (select 1 as d union all select 2 union all select 3 union all               select 4 union all select 5 union all select 6               select 7 union all select 8 unin all select 9 union all select 0              ) d1 cross join               (select 1 as d union all select 2 union all select 3 union all               select 4 union all select 5 union all select 6               select 7 union all select 8 unin all select 9 union all select 0              ) d2 cross join               (select 1 as d union all select 2 union all select 3 union all               select 4 union all select 5 union all select 6               select 7 union all select 8 unin all select 9 union all select 0              ) d3         ) n         where n.num between 1 and occurrences 	0.218992579023692
15207070	19037	fastest way to check if the the most recent result for a patient has a certain value	select      count(1)  from     t_measurements m      inner join (             select patid, max(datemeasurement) as lastmeasureddate from             t_measurements m             where datemeasurement > '01-04-2012'             group by patid             ) lastmeasurements      on lastmeasurements.lastmeasureddate = m.datemeasurement        and lastmeasurements.patid = m.patid where     m.code = 'xxxx' and m.result = 'xx' 	0
15208004	2026	mysql : select records with conditions that applies to multiple rows	select distinct a.parent_id  from details as a join details as b on a.parent_id=b.parent_id where a.data_key='guitar' and a.data_value='4' and       b.data_key='radio' and b.data_value='2'; 	0.00123604984216137
15210243	4663	bayes theorem as a sql query	select * from   eventdetail where  location = 'glasgow'    and doe = '2013-03-18' order by score desc limit 1 	0.476297576033101
15216345	34048	i need to assign a random but unique id to each row of mysql table.the id should be same if the row contains same values	select crc32(concat(column1, column2, column3)) from mytable. 	0
15219835	15138	convert sql server 2008 table column as xml and aggregate xpath values	select t2.x.value('text()[1]', 'nvarchar(10)') from thattablewithxmlinstrings   cross apply (select cast(xmlcolumn as xml)) t1(x)   cross apply t1.x.nodes('/container/data/somenode') as t2(x) 	0.194532287472343
15233040	38650	return parents 3 levels deep in one sql	select a.page_id,concat_ws(' » ',c.page_description_name,                                  b.page_description_name,                                  a.page_description_name) path from page_descriptions a left join pages a1    on a.page_id = a1.page_id and a1.parent_page_id <>1 left join page_descriptions b   on b.page_id = a1.parent_page_id left join pages b1    on b.page_id = b1.page_id and b1.parent_page_id <>1 left join page_descriptions c   on c.page_id = b1.parent_page_id left join pages c1    on c.page_id = c1.page_id  and c1.parent_page_id <>1 where (c1.parent_page_id is null or c1.parent_page_id=0)   and a.page_description_id <> 1 	0.0112279657826284
15243583	20137	phpmyadmin - sum all columns into one column	select sum(<coloumntitle>) as <newcoloumntitle> from <tablename>; 	7.02008181569841e-05
15244609	26958	select records with 2 type of sort	select     a.*,     b.price from table1 as a left outer join (     select           table1_id,         max(price) as price     from table2     group by table1_id ) as b     on b.table1_id = a.id order by a.id asc, b.price desc 	0.000719947261303516
15246991	16692	creating new column with rows shifted up in mysql	select id, `time` as time1, (select min(st.`time`) from t1 st where st.id = t1.id and st.`time` > t1.`time`) as time2 from t1 	0.0238076444219892
15263650	11551	how to perform the following join in mysql?	select  a.id, a.first_name, a.sport,         b.hobby from    tablea a         left join tableb b             on a.first_name = b.name 	0.650591759012848
15274410	1648	select between dates issues	select     *  from     `table` where     expiresdate <= curdate() + interval 10 day order by     expiresdate asc 	0.107296421997923
15279152	21217	loop through sql and calculate sum in php	select employee_id, sum(hours_dev)+ sum(hours_pm) as total  from employee_times where employee_id= '1' group by employee_id 	0.0630122309866169
15283746	23028	how to get info from three tables with a min (mysql)	select i.id, name, category, null as size, min(prices.price) from items i join prices on prices.id = i.id group by i.id, i.name, i.category, size union all select i2.id, name, category, size, min(prices2.price) from items2 i2 join prices2 on prices2.id = i2.id group by i2.id, i2.name, i2.category, i2.size 	6.81024978937306e-05
15291506	30481	sql query to select distinct row with minimum value	select tbl.* from tablename tbl inner join (   select id,min(point) minpoint from tablename group by id )tbl1 on tbl1.id=tbl.id where tbl1.minpoint=tbl.point 	0.000869603492500996
15313043	25508	mysql query to order two column, one asc another desc	select *  from results order by substring( qid from 1  for 1 ) asc , marks desc 	0.00114782236127198
15332951	7541	recovering deleted records	select * from my_table as of timestamp to_date('13-mar-11 08:50:58','dd-mon-yy hh24:mi:ss') 	0.0665817424701663
15338469	36323	how to write a query to show data from table in custom format in sql server 2005?	select empid, empname, catalogname, training1 as training from mytable union all select empid, empname, catalogname, training2 as training from mytable union all select empid, empname, catalogname, training3 as training from mytable order by empid, training 	0.0183121117357101
15339061	20698	dotnetnuke find all pages with specific text	select t.tabname, 'http: from htmltext h join modules m on h.moduleid=m.moduleid join tabmodules tm on m.moduleid=tm.moduleid join tabs t on tm.tabid=t.tabid 	0.00118873026356825
15344850	19172	how to get distinct row from multiple tables in sql server 2008?	select a.another_a_id, b.name   from dbo.tablea as a   inner join dbo.tableb as b   on a.aid = b.aid   group by a.another_a_id, b.name; 	0.000207104816036768
15350112	12555	conversion of large number to julian format in a regexp_replace	select    string,   regexp_substr(string, '^\d*\d+') ||   regexp_substr(to_char(to_date(     regexp_replace(string, '^\d*\d*?(\d{1,3})(\d|$).*$', '100\1'),      'j'), 'fmjth'), '\d*$') ||   regexp_replace(string, '^\d*\d+(.*)$', '\1') as new_string from your_table 	0.0166689643877988
15360883	10464	need to limit the number of rows in each order in following table?	select col1,          col2,          col3  from(     select          col1,          col2,          col3,          row_number() over (partition by col1 order by col1, col2, col3) rnum     from yourtable  )x where rnum<=5 	0
15374902	16433	how do i write an sql query to identify duplicate values in a specific field?	select * from table t1 inner join (     select review_id, deduction_id from table     group by review_id, deduction_id     having count(parameter_id) > 1 ) t2 on t1.review_id = t2.review_id and t1.deduction_id = t2.deduction_id; 	0.00135459092905567
15385191	30259	need optimized query which take data from three tables	select u.id,u.mail,  (select count(1)     from products   where products.leader_id = u.id)  as conteo  from user u   left join account ac  on(u.id = ac.user_id)  having (conteo>3) 	0.0209326680730963
15386787	8177	sql query that can identify distinct values and maximum values	select fleetnumber,         max(traveldate) as traveldate,         substring_index(group_concat(routeid order by traveldate desc), ',', 1) as routeid,         substring_index(group_concat(companyid order by traveldate desc), ',', 1) as companyid from fleetschedule group by fleetnumber; 	0.000184607330694925
15400442	30917	how to divide two values from the same column in sql	select t1.a, t1.b, t1.c,     case when t2.c is null then 0 else t1.c - t2.c end as d,     case when t2.c is null then 0 else (1.0 * t1.c - t2.c) / t1.c * 100.0 end as pct from t t1 left outer join t t2 on t1.a = t2.a     and t1.b = t2.b + 1 	0
15419436	26305	return values where join connection doesn't exist	select groups.* from   groups left join agencygroupjoins using (groupid) where  agencygroupjoins.groupid is null 	0.307482984096478
15419878	32282	how to map two columns using another table in sql?	select ut.user1, uz1.zipcode as zip1, ut.user2, uz2.zipcode as zip2 from user_table as ut join user_zip as uz1 on ut.user1 = uz1.user join user_zip as uz2 on ut.user2 = uz2.user 	0.000244006177131384
15420149	14380	adapting with/cte statement	select top 1    value from (   select     table1.cost, table2.accountnumber     count(*) as frequency,     table1.cost as value   from table1 cross join table2    group by table1.cost, table2.accountnumber, table1.cost  ) t order by    frequency desc,    value desc 	0.746010838617353
15421014	4518	oracle: query a column (type timestamp) of a table	select *   from tablename  where extract( hour from columnname ) = 17    and extract( minute from columnname ) = 0    and extract( second from columnname ) = 0 	0.00237203870705776
15421846	34004	mysql query to find managers who are also employees (not managers) in (an)other department(s)	select works.eid  from works inner join dept using (did) where works.eid != dept.managerid    and works.eid in (select managerid as eid from dept) 	0
15437661	15704	get game_id of a players max(score) in sql	select s.id, t.game_id, t.score from    (         select game_id, score         from game         where player_id =2 order by score desc limit 0,1     ) t left join game s on s.game_id = t.game_id and s.score = t.score 	0.00406223994715496
15440525	17723	select all records where column b only has distinct instances of column a	select a, b from temptable where b in (   select b   from temptable   group by b   having count(distinct a) = 1 ) 	0
15442760	28948	get the correct last id from table	select max(lastid) from my_table 	0
15466543	10871	mysql - sum values width same id in same table	select    sum(value_o) as value_o,    sum(value_t) as value_t,    sum(value_tt) as value_tt  from   (   select id, value_o, value_t, value_tt from table1    union all    select id, value_o, value_t, value_tt from table1   ) table2  where id in(1, 1); 	0
15467702	4837	select statement with max function	select p.clientid    ,lastname+' '+firstname as name     ,address    ,max(p.pickupdate) from pickup p join clients c on p.clientid= c.clientid group by p.clientid, lastname + ' ' + firstname,address having max(p.pickupdate)<dateadd(month,-2,getdate()) 	0.790628601508185
15475544	33689	select filed name from sql table	select column_name from information_schema.columns where 1=1     and table_name = 'master'     and column_name in ('shiftdiffind','nontaxytodate') 	0.00585233157783737
15490318	25790	how to fill bed number column for patients table in a hospital database according to the occupied dates of a particular bed	select bed_id from bed minus select bed_id from bed_occupancy where enter_datetime is not null and departure_datetime is null 	0
15496875	36639	converting a string to datetime in sql	select    messagetext,    convert(     datetime,     substring(       messagetext,        charindex('(', messagetext) + 1,        charindex(')', messagetext) - charindex('(', messagetext) - 1),     103)    as tourtimestamp,    timestamp  from    tblmessagelog  where    messagetext like 'tour run timestamp%for tour%has been%'  order by timestamp desc 	0.165030527640962
15497825	41234	select greatest date	select db.person, address, from_date,db.to_date   from db, (select person, max(to_date) to_date             from db            group by person) db_max where '2000-01-01' between db.from_date and db.to_date   and db.to_date = db_max.to_date   and db.person = db_max.person; 	0.0282810921342425
15499401	30753	get field in a single row from union query	select     (select  count(gi.id)     from    group_info as gi     where   gi.domain_status_id = 1 and          gi.group_status_id = 1 and          gi.group_creation_date <= '2013-01-31' and          gi.project_info_id = 'bi0000000000000000000001' and         gi.branch_info_id = 'bi0000000000000000000363')  as no_of_group     ,(select  count(outerlat.member_info_id)     from         (select lat.member_info_id, max(lat.id) as max_member_id  from loan_account_transaction as lat          where lat.project_info_id = 'bi0000000000000000000001' and lat.country_id = 1 and lat.domain_status_id = 1         and lat.office_info_id = 'bi0000000000000000000363' and lat.transaction_date <= '2013-01-31'      group by lat.member_info_id) as tempdata     inner join loan_account_transaction as outerlat       on (tempdata.max_member_id = outerlat.id )     where   outerlat.loan_status_id in(1,3,4,5)) as no_of_borrower 	7.98037765158708e-05
15524509	18828	query sql xml field on type	select top 100 * from dbo.table with (nolock) where response.exist('/errormessage') = 1 	0.112035737886364
15525358	12508	compare subsequent rows in sqlite with joins	select t1.a,        (select t2.a from t t2 where t2.a > t1.a order by t2.a limit 1        ) as nexta from t t1 	0.058159623221512
15533401	8175	changing order output, using if or something that	select *, kills-deaths as x  from users  order by x = 0, x desc limit 0,50; 	0.478445918794861
15560966	14837	return mysql rows within 10% of a given value	select * from `tblname` where `rating` between 13 * 0.9 and 13 * 1.1 	0
15562270	13315	php date('w') vs mysql yearweek(now())	select yearweek(now(),3); 	0.776711809922821
15566233	40802	join data from 2 mysql tables	select mail_id, titel, status, subscriptions.datum from subscriptions join mail on (subscription.mail_id=mail.id)     where klant_id = '".$_get["id"]."' group by mail_id 	0.00527765737268051
15569494	3033	need to crc32 integer column and substr the result	select substr(crc32(id),1,2) from table limit 10; 	0.572442905313085
15571471	23128	find last row in group by query-sql server	select id, name  from (select id, name,               row_number() over (partition by name order by id desc) as max_id       from customer) x where max_id = 1 	0.000218267692026994
15591494	15397	table structure for a quiz based app	select * from options where question_id = x 	0.0475225855550858
15608958	9680	sql server select by grouping	select status, sum(plotsize) as totalplotsize  from csstatus cs  inner join csplotdetials cp on cs.csid = cp.csid  group by status 	0.320581866821858
15609336	15790	sql find nearest number	select name, max(value) from tbl where value <= 3 group by name 	0.00502411318250428
15620656	38923	sql query through another table	select student.programmeid, avg(grade.gradepercent) from student inner join grade on student.studentid = grade.studentid group by student.programmeid 	0.0306734859107983
15621488	5402	4 table join with fixed table construct	select s.student, c.title from student s, attendance a, course_offering co, course c where s.student_id  = a.student_id and   a.offering_id = co.offering_id and   co.course_id  = c.course_id and   s.student_id = "insert id here"; 	0.0838777600624633
15628820	17995	get relational data with mysql join?	select  a.name, a.content,         b.name as categoryname from    pages a         inner join pagecategories b             on a.id = b.pageid         inner join categories c             on b.categoryid = c.id 	0.119344799315964
15631945	19280	get count in one to many relation in sql	select  case when coalesce(b.totalcoupons, 0) > 3 then company.name +' (important) '         when ishighpriority = 1 then company.name +' (high priority) '         else company.name +''     end  as companyname , company.id as companyid from    company company     left join     (         select  co.name as coname, co.id as coid, count(c.id) totalcoupons         from    company co, coupon c         where c.companyid = co.id   and c.rejectedprocessed = 1 and c.reviewverify = 0 and c.ispublish = 0 and c.forsupervisor = 0          group   by co.name, co.id     ) b on company.id = b.coid 	0.0026391039573564
15632427	39941	filling gaps between data ranges in mysql	select   r1.end_date + interval 1 day d1, min(r2.start_date) - interval 1 day d2 from   ranges r1 inner join ranges r2   on r1.end_date <= r2.start_date group by   r1.end_date having   datediff(min(r2.start_date), r1.end_date) > 1 	0.000374874075006099
15641539	3994	select distinct values and order by the same column(value)	select slide_name, slide_no from (select * from ( select *     from tablename     group by slide_no, slide_name      order by rand() ) `temptable`  ) x group by slide_no order by slide_no asc limit 4 	0.000718274126279355
15652400	16759	splitting values to a column with case statement in sql server	select     recordid     , productname     , books = case when future06 like '%418%' then future06 else null end     , video = case when future06 like '%421%' then future06 else null end from     schema.dbo.table1 	0.307193755986558
15667235	37728	separate one column to two by row's value	select   p.id,   p.title,   mr.value as result,   me.value as end from posts as p inner join meta as mr   on mr.post = p.id   and mr.`key` = 'result' inner join meta as me   on me.post = p.id   and me.`key` = 'end'; 	0
15669826	40965	how do i write a sql query for an attribute in a table containing only part of a word in sql server	select * from products where descrip like '%racket%' 	0.00079751122892323
15684419	10222	what to use: record or cursor?	select   p.idpledge,   p.iddonor,   p.pledgeamt as this_payment,   case      when p.paymonths = 0 then 'lump sum'     else 'monthly - ' || p.paymonths    end as payment_method from   dd_pledge p where   trunc(p.pledgedate) >= '01-mar-2010' and trunc(p.pledgedate) < '01-apr-2010'   order by   4 	0.78854401072723
15688467	8354	sql query hourly for each day	select spa.startdate, c.hour as starttime, spa.idsession as sessionid from calendar c join      @sessionsperarea spa      on c.hour between spa.starttime and spa.endtime 	7.78912089898345e-05
15689624	41202	using wildcard in table data	select id, model from your_table where 'dv209aww' like model order by id 	0.271671862575913
15696687	8997	mysql select from where different	select c.* from order as o join customers as c on o.customers_id = c.customers_id where o.customers_id not in(select customers_id from testimonials) 	0.00963893179926886
15705244	36526	compare a column in two different tables	select  * from    a full join         b on      a.ip = b.ip where   a.ip is null or b.ip is null 	7.96108178098183e-05
15719557	8397	how to compute the sum of multiple columns in postgresql	select coalesce(col1,0) + coalesce(col2,0) from yourtable 	0.00161377578839552
15739396	2224	get employees who worked in more than one department with sql query	select e.employeename, count(departmentno) from employee e    inner join department d on e.employeename=d.employeename    group by e.employeename    having count(departmentno)>2 	5.38354332923435e-05
15741314	7294	mysql concat returns null if any field contain null	select concat_ws('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) as device_name from devices 	0.221619145679979
15747047	9543	how can i add a where clause for each row in a subquery?	select t1.id, t1.content, ts_a.tag, ts_b.tag, ts_c.tag, ts_d.tag, ts_e.tag from content t1 left join tags ts_a on t1.tag_a_id=ts_a.id left join tags ts_b on t1.tag_b_id=ts_b.id left join tags ts_c on t1.tag_c_id=ts_c.id left join tags ts_d on t1.tag_d_id=ts_d.id left join tags ts_e on t1.tag_e_id=ts_e.id where "news" in (ts_a.tag, ts_b.tag, ts_c.tag, ts_d.tag, ts_e.tag) and "medicalcare" in (ts_a.tag, ts_b.tag, ts_c.tag, ts_d.tag, ts_e.tag) 	0.00273567570332756
15747688	28673	mysql query when grouping duplicate records	select a.*,b.sku from sku_parent_attributes as a inner join sku_parent_attributes as b on a.sku = b.sku group by b.sku having count(b.sku) = 3 	0.0161748488647239
15765423	23865	get all parent records from child record	select *   from tbl1  start with note_text like '%z%'  connect by note_id = prior parent_note_id 	0
15776578	16276	grabbing child-nodes of parent using the adjacency model in mysql	select c1.*, c2.id from category c1 inner join category c2 on (c1.parent = c2.id); 	0.0120559414921161
15792249	5004	how to see co-relation between course grades?	select qcp.* from (select rollnum, cgpa, status, name, finalgrade       from db       where name = 'computer programming'        and finalgrade = 'a') qcp inner join      (select rollnum       from db       where name = 'introduction to computer science'       and finalgrade = 'a') qintro on qcp.rollnum = qintro.rollnum 	0.0100894701752258
15799556	6617	postgresql join data from 3 tables	select t1.name, t2.image_id, t3.path from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id inner join table3 t3 on t2.image_id=t3.image_id 	0.0157281321574414
15799874	36640	django: order a queryset by the sum of annotated fields?	select  id, name,     total_messages, total_discussion_approval_votes, total_message_approval_votes,     (total_messages +      total_discussion_approval_votes +      total_message_approval_votes) as score_total from    (select     discussion.id,     discussion.name,     count(distinct discussionapprovalvote.id) as total_discussion_approval_votes,     count(distinct messageapprovalvote.id) as total_message_approval_votes,     count(distinct message.id) as total_messages     from discussion     left outer join discussionapprovalvote          on (discussion.id = discussionapprovalvote.discussion_id)     left outer join message          on (discussion.id = message.discussion_id)     left outer join messageapprovalvote          on (message.id = messageapprovalvote.message_id)     group by discussion.id, discussion.name) order by score_total desc limit 20; 	0.0216214023229876
15801356	38029	mysql getting rank from score	select y.score, y.score/z.maxscore perc,    @rn:=@rn+1 rn,   @rnk:=if(@score=y.score,@rnk,@rn) rnk,   @score:=y.score from yourtable y   cross join (select max(score) maxscore         from yourtable) z   join (select @score:=-1,@rnk:=0,@rn:=0) t order by 2 desc 	0.00724828106990495
15810271	7007	selecting value via substracting another value from a total number	select id from fa where mass = 800 - (select mass from fa where id = '14:0') 	0
15812209	33652	mysql: complete missing data with parent tables	select cities.name, coalesce(cities.tax_rate,states.tax_rate,countries.tax_rate) from cities join states on cities.state_id=states.id join countries on states.country_id = countries.id 	0.0797327426114767
15817003	16306	extract 1st three octects of an ipv4	select inet_ntoa(inet_aton(ipfield) & 0xffffff00) 	0.0436151851653556
15836349	35115	week based count	select   weeks,   nvl(cnt, 0) as delay_count from   (select level-1 as weeks from dual connect by level < 17)   left join (     select        nvl(least(attr11.value, 15), 0) as weeks,       count(0) as cnt     from        docs        left join (         attributes attr11          join attribute_types atr_tp using(attribute_type_id)       )          on atr_tp.name_display_code = 'attribute_type.delay in weeks'         and docs.obj_id = attr11.object_id     group by nvl(least(attr11.value, 15), 0)   ) using(weeks) order by 1 	0.00032428726510548
15840660	33384	cleaning csv string/varchar in sql	select replace(columnname, ', ,', ', ') from   tablename 	0.752074595251469
15842545	21174	duplicating the result when adding two tables	select * from post_posts, post_cat where post_posts.<primary key col name> = post_cat.<foreign key col name> and post_cat = $id 	0.0116461853650315
15855360	23734	how to get the max of different columns	select  movie ,       max(dt) from    (         select  movie         ,       date-last-downloaded as dt         from    lastdownloaded         union all         select  movie         ,       date-last-purchased         from    lastpurchased         ) subqueryalias group by         movie 	0
15874082	27540	how to split amount to months using query?	select decode(flag, 'original', null, id), months, amount from(     select id,             months,             add_months(to_date('2013-04','yyyy-mm'), n.l-1) as month_name,            amount/months as amount,             'splitted' as flag     from your_table t     join (select level l from dual connect by level < 1000) n     on (t.months >= n.l)     union all     select id, months, amount, null, 'original'     from your_table ) order by id, months; 	0.000693660666878026
15876781	5151	sql minus 2 columns - with null values	select isnull([row 1], 0) - isnull([row 2], 0) from yourtable 	0.0153958024282208
15881964	9656	mysql - find out if input exists in last 30 records	select * from (select *         from login_users         order by registration_date desc         limit 30) a  where a.ip = '".$ip."' 	0
15884541	41211	produce a list of colours against all other colours	select distinct a.t_name as "home", s.t_name as "away" from teams a, teams s where a.t_name <> s.t_name  order by a.t_name; 	0.000277362236942766
15891506	11148	how to optimize the count query for each categories for the search results?	select    count(*)    ,category_id  from     ads  where     title like '%keyword%'  group by category_id 	0.00113847502172894
15891637	34050	correct way to fetch posts which are posted 3 days ago?	select * from track where   from_unixtime(date,'%y-%m-%d') = curdate() - interval 2 day 	0
15908504	20366	finding code that will fire off sql server triggers	select name from sys.procedures where object_definition(object_id) like '%<table_name_here>%' 	0.308480807847361
15914204	38117	how to use the sql random() function in a netbeans javadb	select * from java2.fortunes order by random() offset 0 rows fetch next 1 row only 	0.730097616494258
15933190	4011	representing id's based on a prefix microsoft sql server 2008	select    id,   coid,   partnercoid,   mc.prefix as coprefix,   pc.prifix as partnerprefix from table t join prefixtable mc   on t.coid = mc.coid join prefixtable pc   on t.partnercoid = pc.coid 	0.0363727151987106
15952183	13743	codeigniter 2.1, mysql - two left joins	select kat.*, c.*, count(k.id_komentar) broj_komentara from... 	0.750086398586824
15969560	1870	mysql join at a loss	select * from cases  where case_user in  (select user_id from users where user_company=(    select user_company from users where user_id=27)  ) 	0.191813817257581
15969614	23066	in sql, how to select the top 2 rows for each group	select * from   test s where          (             select  count(*)              from    test  f             where f.name = s.name and                    f.score >= s.score         ) <= 2 	0
15972753	28035	check if mysql datetime is > 1 hour old using php	select *, if(hour(timediff(now(), datetimefield)) >= 1, 1, 0) as olderthananhour 	0.00679840659209912
15981441	22934	how to get multiple values along with null values in sql server and ssrs	select * from table a inner join dbo.ufn_split(@list,'|') s on a.pkey = s.value 	0.000200614505177709
15990143	40564	sql query isn't displaying correct data	select r.idr, r.recipetitle from recipe r inner join recipingr ring     on ring.idr = r.idr inner join ingredient ing     on ing.idi = ring.idi where ing.ingrdesc like '%honey%' or ingrdesc like '%mustard%' order by r.idr 	0.670758597585322
16006959	36336	function to_days mysql on sql server	select datediff(d,'1900-01-01', '2013-04-14') 	0.349684941104191
16009087	28202	running number on oracle union	select col1,        col2,        col4,        row_number() over (order by sort_column ) "row_number" from   (      select col1,             col2,             col4,             sort_column      from table_a      union all      select col1,             col2,             col4,             sort_column      from table_b   ) 	0.135822050784845
16009898	39278	max value using self join	select max(latest) from ( select @latest:=case when @latest=order_id then new_order_id else @latest end    as latest from billing_order_history, (select @latest:=55 ) as t order by order_id) as t1; 	0.423937712042951
16014393	11864	mysql dynamic select	select l.id,  case      when split_str(l.lookup,'.',1) = 'tablea' then tablea.id      when split_str(l.lookup,'.',1) = 'tableb' then tableb.id      when split_str(l.lookup,'.',1) = 'tablec' then tablec.id      when split_str(l.lookup,'.',1) = 'tabled' then tabled.id      else null end as subid from look as l  left outer join tablea on tablea.cola = l.attvalue left outer join tableb on tablea.colb = l.attvalue left outer join tablec on tablea.colc = l.attvalue left outer join tabled on tablea.cold = l.attvalue 	0.494079621766712
16034135	22537	calculate balance from debit and credit column and select users in mysql?	select   * from   accounts where   credit-debit > 1 	0.000464173805504899
16039679	18358	access relationships	select orders.orderid, orders.orderdate, suppliers.suppliername from orders inner join suppliers on orders.supplierid = suppliers.supplierid 	0.447139687472873
16042979	17853	convert a obscure? date format in a sql query to a human readable one	select cast(cast(bigintdateval as char(14)) as datetime) 	0.121696571294001
16049350	36241	in mysql, can i create an index on a timestamp function	select * from table where date between 'xdate' and 'ydate'    and case when date = 'xdate' then timestamp(date, time) >= 'x'             when date = 'ydate' then timestamp(date, time) <= 'y'            else 1 end; 	0.399967306289154
16050419	8088	query sql in oracle	select well_dprod_date,        formation_name,        case          when r1 = 1 or r2 = 1 then           formation_name          else           null        end as formation_name_f  from (select well_dprod_date,            formation_name,            rank() over(partition by formation_name order by well_dprod_date asc) as r1,            rank() over(partition by formation_name order by well_dprod_date desc) as r2           from data_dprod) t 	0.712958269413212
16057219	14054	sorting a sql query by number of fields in a grouped selection	select product, count(*) as numberofentries  from products  group by product  order by numberofentries desc 	0.000976379395422862
16066276	37395	mysql query select all fields with same value	select conversation_id, count(distinct recipient_state) as nb, recipient_state from xf_conversation_recipient group by conversation_id having nb=1 and recipient_state='delete' 	0.000394690736383827
16084444	2822	mysql select top two people with most submitted videos, where type=1	select by_person, count(*) as total from videos where type = 1 group by by_person order by total desc limit 2 	0.000769833186076138
16093813	23844	how to find the next available integer in mysql table using php	select t1.id+1 as missing_id from the_table as t1 left join the_table as t2 on t1.id+1 = t2.id where t2.id is null order by t1.id limit 1; 	0
16124350	14000	sql retrieve and perform arithmetic on values from associated table	select      re1.occured_at as started_at,      re2.occured_at as finished_at,     (re2.occured_at - re1.occured_at) as race_time,     p.id,     p.membership_id,     p.race_id participant_id from participants p  inner join race_events re1 on re1.participant_id = p.id and re1.event_type = 'start' inner join race_events re2 on re2.participant_id = p.id and re2.event_type = 'finish' 	0.000459174998400374
16132417	7560	fetch values from different tables with same id	select user.email, user.username, tweets.message, tweets.date, userdetails.profile_img,userdetails.firstname, userdetails.lastname, '' as id, '' as user_id, '' as follow_id from user join userdetails on user.id = userdetails.user_id join tweets on userdetails.user_id = tweets.user_id where user.id = 1 union all select  user.email, user.username, tweets.message, tweets.date, userdetails.profile_img,userdetails.firstname, userdetails.lastname, following.id, following.user_id, following.follow_id from user join userdetails on user.id = userdetails.user_id join tweets on userdetails.user_id = tweets.user_id join following on user.id = following.user_id and following.follow_id = 1 	0
16139138	20122	how to get desired result from this query?	select * from documents d left join sr s on d.relationid = s.srid left join events e on d.relationid = e.eventid 	0.14383484916025
16145150	6843	how can i query adjacent hierarchical data from two tables where one row is a category and the rest are contents of that category?	select    coalesce(c3.name, c2.name, c1.name) as main   ,case when (c3.name is null and c2.name is null) then lex.word end as main_content   ,case when (c3.name is null and c2.name is not null) then c1.name          when (c3.name is not null and c2.name is not null) then c2.name end as sub1   ,case when (c3.name is null and c2.name is not null) then lex.word end as sub1_content   ,case when (c3.name is not null and c2.name is not null) then c1.name end as sub2   ,case when (c3.name is not null and c2.name is not null) then lex.word end as sub2_content from   lexicon lex left join    categories c1 on lex.pid = c1.folder left join   categories c2 on c1.pfolder = c2.folder left join   categories c3 on c2.pfolder = c3.folder 	0
16154801	6608	list customers that purchased orders > the average paid order	select c.cust_lname, c.cust_fname, o.amount from customer c join      orders o      on c.customerid = o.customerid where o.amount > (select avg (o.amount)                   from orders o) 	0
16160650	40513	mysql sorting alphanumeric transaction code using date indicator	select code from table order by substr(code, 1, 9), substr(code, 10, 6) desc, cast(substr(code, 16) as decimal) desc; 	0.527173849516671
16163094	35880	mysql sum() and join in one query	select   teams.name,   sum(standings.points) as standingpoints,   standings.seasonid,   teams.leagueid from teams   inner join standings     on teams.id = standings.teamid group by teams.id having teams.leagueid = 0     and standings.seasonid = 0 order by standingpoints desc limit 3 	0.136113496902651
16177321	28958	c# extract month no values	select sum(skupaj)  from [cas] where sifra = 123  and month(datum) = 4 	0.000357457177005689
16181684	14510	combine many tables in hive using union all?	select * into tmp_combined  from  (     select b.var1 from tmp_table1 b     union all     select c.var1 from tmp_table2 c     union all     select d.var1 from tmp_table3 d     union all     select e.var1 from tmp_table4 e     union all     select f.var1 from tmp_table5 f     union all     select g.var1 from tmp_table6 g     union all     select h.var1 from tmp_table7 h ) combinedtable 	0.0302056307013747
16185850	40222	sqlite on android: different result set at runtime vs. sqlite administrator	select distinct i.id as 'image id', i.imagename, v.id as 'video id', v.videoname from tblimages i left join tblimagevideolink l on l.imageid=i.id left join tblvideos v on l.videoid=v.id where i.page=1; 	0.178390711521019
16200260	23424	sql left and right parts list from a single list (all parts listed)	select pl.[part],pl.[side], pl.[batch], pl.[lot], pr.[part] as part_r, pr.[side] as side_r, pr.[batch] as batch_r, pr.[lot] as lot_r from    (select * from part where side = 'left') pl full outer join    (select * from part where side = 'right') pr   on pl.batch = pr.batch    and pl.lot = pr.lot 	0.000100636873975
16212594	17592	select multiple values from same column based on 2 columns	select    p.name,   (select value from attributes a where attr_id=101 and a.prod_id=p.id) as price,   (select value from attributes a where attr_id=102 and a.prod_id=p.id) as taste from products p 	0
16234419	2763	i need to select one column considering repeated values in another column	select min(parameterid) as parameterid from [<yourtable>]  group by hdfid 	0
16235135	13512	how to run a nested query depends on a condition	select case when t1.id = t2.id and t1.score = t2.score then t1.amt else t1.time end fieldalias from yourtable t1 join yourtable t2 on something where whatever 	0.423546823474326
16241061	23202	classic asp select * where x and x	select * from reviews where [month]=x and [year]=x 	0.0318814263162748
16245415	38712	display 1 if all grouped rows are 1 otherwise display 0	select min(paid), sum(services.amount) as service_amount from invoices left join projects using(project_id) left join services using(invoice_id) where client_id = ? group by project_id order by issue_date desc 	0
16245543	4818	simple/ish command	select m.master_data, c.child_data from master_table m left outer join child_table c      on m.id = c.id where c.child_data is null 	0.568133339448328
16270343	39140	how to know which part of query is executed	select status,     case      when (userid=1 and friend=2) then 'opt1'     when (friend=2 and userid=1) then 'opt2' end as 'var' from friends  where userid in (1, 2)      or friend in (1, 2) 	0.155535634246665
16288969	29244	comparing duplicate rows in one table, and returning values in another table	select *  from table2   where table2.id not in (select distinct table1.id                          from table1                          where table1.checkin > sysdate or                            table1.checkout > sysdate) and  table2.id in (select distinct table1.id                from table1) 	0
16294594	26434	getting result close to certain number	select  a.* from    searching a         inner join searching b             on a.feature between b.feature - 2 and b.feature + 2 where   b.name = 'gore' 	0.000512520766257222
16298943	1778	oracle: create sequence number for repeated rows	select id, value, row_number() over (partition by value order by id) as seq from your_table; 	0.00262647423418174
16301169	7246	count row with content for specific number of columns	select sum(case when a is  null then 0 else 1 end)       + sum(case when b is  null then 0 else 1 end)       + sum(case when c is  null then 0 else 1 end)       as [total] from dbo.sometable 	0
16308363	10364	fulltext postgres	select * from chamado where to_tsvector('portuguese', titulo) @@ to_tsquery('portuguese', 'ura') 	0.738200042652721
16340555	20918	return binary as string, not convert or cast	select sys.fn_varbintohexstr (0x24fc40460f58d64394a06684e9749f30) 	0.377459957530565
16342769	19567	force query to deliver duplicate results based off where values	select   a.accountnumber,   a.programflag,   a.applicationstatus from   dbo.accountinfo as a inner join    (values('100'),('101'),('101'),('101'),('102'),('102'),('103')) as t(accountnumber) on   a.accountnumber = t.accountnumber order by   a.accountnumber asc; 	0.00173017978552885
16344075	7532	mysql logic - how to change the selected value based on the data?	select case              when exists (select *                            from contact_numbers                           where main_number = 1                             and contact_number =                             <insert contact number from outer expression here>)              then 1             else 0         end as mainnumber   from ... 	0
16373034	16154	i want to make a sum from 5 tables that have one column named "up"	select  sum(sumup) from    (         select  sum(up) as sumup         from    table1          union all         select  sum(up)         from    table2         union all         select  sum(up)         from    table3         union all         ...         ) subqueryalias 	0
16383624	15567	mondial db inner query	select      country.name, city.cityname, city.population from     country join city on country.code = city.country join (select          max(population) as population,country as country from city group by country)  as x on city.country = x.country and city.population = x.population 	0.770969288177612
16386757	16553	mysql group by without removing duplicates	select user, score from guesses order by score 	0.206575405828401
16397101	14224	match delimeter(|) separated values field in mysql select query	select id from your_table where find_in_set('3', replace(skills, '|',',') > 0 select id from your_table where find_in_set('3', replace(skills, '|',',')) > 0 or find_in_set('5', replace(skills, '|',',')) > 0 	0.00042887552159266
16398661	19022	sql - find date closest to current date	select  * from    table1 order by         abs(now() - date) desc limit   1 	0
16404876	14793	ordering query results by row repetitions without join	select user1, rev1, user2, rev2, count(*) over (partition by user2) as c from sometable where something1 = something2 order by c desc 	0.186911404860304
16414376	34299	how to order my table (sql and js)	select * from table_name order by field_name desc 	0.648946507182352
16422260	3885	creating table with correct data	select callcenter, substr(phonenumber, 1, 1) as startswith, count(*) as number from mytable group by callcenter, substr(phonenumber, 1, 1) order by 2, 3 	0.404847920306863
16442688	2411	how to add 1 day to current date and have result in format yyyymmdd in sql server?	select @dat = dateadd(dd, 1, getdate()) declare @datcus varchar(8) select @datcus=left(convert(varchar(8), @dat, 112),10) 	0
16446826	9601	ms access combine tables with like fields	select clientid, thedate, payment, cost from (   select paymentdate as thedate, amount as payment, 0 as cost, clientid   from payment   union all   select bookeddate as thedate, 0 as payment, cost, clientid   from [all bookings query] ) order by thedate desc; 	0.406587171666761
16452844	36516	postgres dynamic sql and list result	select * from test2('select * from test') s(a int, b text, c text);  a |  b   |  c     1 | safd | sagd  2 | hdfg | sdsf 	0.173841311242824
16457514	14379	multiple columns with foreign key to the same table	select user_id, ( select menu_name from menu where menu_id = explorer_menu_id ) as explorer_menu_name, ( select menu_name from menu where menu_id = tablet_menu_id ) as tablet_menu_name from user 	0
16459016	11702	how to use unpivot convert column to row sql server?	select  empno, chkdate, cdate = chkin from ta_filltime union all select  empno, chkdate, cdate = chkout from ta_filltime order by  empno, chkdate 	0.0863516602699979
16479372	17090	see all indexes and appropriate columns for table	select * from pg_indexes where tablename = 'mytable'; 	0.0233235216134674
16487804	24316	sql enrollment caps	select t1.classid, t1.sln, t1.capacity from table1 t1 where not exists (select 1                     from table2 t2                   where t1.sln = t2.class)   or t1.capacity > (select count(*)                       from table2 t2                     where t1.sln = t2.class                     group by class); 	0.326403661504077
16487813	35567	before a date in oracle sql	select * from  (   select (trunc(sysdate)-2)                      start_dt         , (trunc(sysdate)-2)-level                bus_days         , to_char((trunc(sysdate)-2)-level, 'dy') wk_day    from dual   connect by level <= (trunc(sysdate)-2)-((trunc(sysdate)-2) - 7)   ) where wk_day not in ('sat', 'sun') order by bus_days / start_dt    bus_days    wk_day 5/11/2013    5/6/2013    mon 5/11/2013    5/7/2013    tue 5/11/2013    5/8/2013    wed 5/11/2013    5/9/2013    thu 5/11/2013    5/10/2013   fri 	0.0922666110717105
16489420	18639	select data from two tables. one table is parent/child and i need to get the parents without a relation	select p.*,c1.cat_name as category, c2.cat_name as parent_category from products p left join categories c1 on (c1.id=p.catid) left join categories c2 on (c1.parent=c2.id) 	0
16496874	38008	how to select max of mixed string/int column?	select max(cast(substring(invoice_number, 4, length(invoice_number)-3) as unsigned)) from table 	0.00730007431721461
16499172	4431	mysql. insert and select data to database without duplicates	select username,min(time) time from eurokos group by username order by time asc limit 10; 	0.0189474726448719
16500186	5145	sql server update foreign key to point to the first in a set of duplicated items	select row_number() over(partition by #imagetag.tagname order by #imagetag.tagname) as tagrank, #imagetagmap.imagetagmapid, #imagetagmap.imageid, #imagetag.tagid, #imagetag.tagname into #updatetable1 from #imagetagmap     join #imagetag on #imagetagmap.tagid = #imagetag.tagid select #updatetable1.tagid as idtodelete, rowtokeep.tagid as idtokeep into #updatetable2 from #updatetable1     join (select * from #updatetable1 where tagrank = 1) rowtokeep on #updatetable1.tagname = rowtokeep.tagname where #updatetable1.tagrank != 1 update #imagetagmap set tagid = #updatetable2.idtokeep from #imagetagmap     join #updatetable2 on #imagetagmap.tagid = #updatetable2.idtodelete select * from #imagetagmap     join #imagetag on #imagetagmap.tagid = #imagetag.tagid delete #imagetag from #imagetag     left outer join #imagetagmap on #imagetag.tagid = #imagetagmap.tagid where #imagetagmap.imagetagmapid is null 	0
16513601	11089	search multiple tables in mysql database	select * from user_initials inner join user_data on user_initials.user = user_data.user where user_data.user = 'kashif' 	0.0866756188495706
16522003	28263	case expressions on datetime columns	select case      when next_action_date between getdate() and getdate()+7 then 'incoming'     when next_action_date < getdate() then 'overdue'     else 'fine' end as condition from(     select getdate()+6 next_action_date )x 	0.362178706787372
16523420	29064	hql, how to write join query between tables that has one to many relationship?	select a from author as a join a.book as ab where ab.authorid like '%"hello"%'; 	0.0101310602417998
16544836	27969	comapring one table in 2 schemas to find missing coluns	select table_name, column_name, data_type, data_length   from all_tab_columns  where owner = 'schema1' minus select table_name, column_name, data_type, data_length   from all_tab_columns  where owner = 'schema2' 	0.000311832896500588
16547911	4008	how to merge a select statement with a new dynamic values as columns?	select distinct      a.hirelastname,      a.hirefirstname,      a.hireid,      a.position_id,      a.barnumber,      a.archived,      a.datearchived,      b.position_name,     cast((select count(*) from hire_response where hireid = a.hireid and         (hireresponse = 0 or hireresponse = 1)) as float) /       cast((select case when count(*) = 0 then 1 else count(*) end from hire_response where hireid = a.hireid) as float) as myspecialcolumn from newhire a  join position b on a.position_id = b.position_id join workperiod c on a.hireid = c.hireid where a.archived = 0 and c.inquiryid is not null  order by a.hireid desc, a.hirelastname, a.hirefirstname 	0.00120785427774551
16565916	23928	how to select one image of a object stored in another table	select product.id,product.name, (select top (1) image from productimage where productimage.productid=product.id order by productimage.id asc)as firstimage , (select top (1) image from productimage where productimage.productid=product.id order by productimage.id desc) as lastimage from product 	9.24042195510685e-05
16579596	28262	sql query to compare two rows under different condition	select count(t1.projectid) from (select projectid ,sum(totalday) as tl1 from project where location=1 group by projectid ) t1 inner join (select projectid ,sum(totalday) as tl2 from project where location=2 group by projectid ) t2 on  t1.projectid=t2.projectid  and t1.tl1>t2.tl2 	0.000192330088106414
16584549	30283	counting number of grouped rows in mysql	select count(*) from( select distinct component from `multiple_sample_assay_abc` where labref = 'ndqa201303001' ) 	5.01474665756202e-05
16594532	8850	the database is case sensitive in unique constraints but not in select	select      name, collation_name from        sys.columns where       object_id in (select object_id from sys.objects where name = '<table name>') and name = '<field name>' 	0.703469449518853
16621486	17496	sql oracle query to find receipts	select trunc(receiptno/1000) booknumber, count(distinct purchaseno) numpurchases from purchase group by trunc(receiptno/1000) having count(distinct purchaseno) >= 10 order by 1 	0.206433344465074
16631903	21124	sql selecting average of rating from another table	select l.animeid,         l.name,         l.animeimage,         l.synopsis,         l.type,         l.episodes,         l.genres,         (select isnull(avg(rating), 0) rating           from anime_reviews           where animeid = l.animeid)   from anime_list l 	0
16637466	6936	selecting latest conversations from table containing private messages	select least(`from`,  `to`), greatest(`from`, `to`) from  `pms`  where  `from` = 1 or  `to` = 1 group by  least(`from`,  `to`), greatest(`from`, `to`) order by max( `id`) desc  limit 10 	0
16639641	1123	sql server: how i create a horizontal table	select sensorid,         [00], [01], [02], [03], [04] from mytable pivot (   max(value)   for date in ([00], [01], [02], [03], [04]) ) as pivottable; 	0.0447778703855104
16648566	375	mysql - get last message from all users	select   u1.displayname as sendername,   m.date_sent,   ... from messages as m1 inner join users as u1 on m1.sender_id = u1.id (    select sender_id, max(datesent) maxdate    from messages     group by sender_id    where receiver_id = 4 ) as m2  on m1.sender_id = m2.sender_id         and m1.datesent  = m2.maxdate 	0
16651665	5891	use distinct properly joining multiple tables	select p.* , t.*, s.* from f_posts p inner join (select post_topic, max(post_date) max_date             from f_posts             group by post_topic             order by max_date desc limit 0,3) m         on p.post_topic = m.post_topic and p.post_date = m.max_date inner join f_topics t on p.post_topic=t.topic_id inner join f_subcategories s on s.scat_id=t.topic_scat order by f_posts.post_date desc 	0.6268647617781
16659380	27276	group by and limiting the output in mysql	select foodgroup, count(*) as mycount from food group by foodgroup having mycount > 49 	0.293062550581779
16667171	15784	joining 2 tables and show the same column repeatedly based on its associative id	select user.user_id,        item_equipped.head,        item_heads.item_id head_item_id,         item_heads.item_name head_item_name,               item_equipped.hand,        item_hands.item_id hand_item_id,          item_hands.item_name hand_item_name   from user, item item_heads, item item_hands, item_equipped  where user.user_id = item_equipped.user_id    and item_heads.item_id = item_equipped.head    and item_hands.item_id = item_equipped.hand 	0
16669042	40921	vietnamese characters in sql select like	select * from [table] where name like n'%hà nội t&t%' 	0.585975450326533
16687762	13986	selecting all values in groupby	select  id, [desc], terminationdate, lastupdtdt from         (             select  id, [desc], terminationdate, lastupdtdt,                     row_number() over(partition by id                      order by lastupdtdt desc) rn             from    tablename         ) ss where   rn = 1 	0.00202652278859403
16712270	40000	mysql excludes first parameter when using and & or like in same query?	select *  from links  where links_public = '1'  and (links_description like '%$filter%'  or links_created_by like '%$filter%' or links_link like '%$filter%' )  order by links_created desc 	0.421770867914491
16714244	36218	connecting multiple tables and using self join	select a.actorid, b.actorid, count(*) mostfilms from casting a inner join casting b  on a.movieid = b.movieid and a.actorid < b.actorid group by a.actorid, b.actorid order by mostfilms desc limit 1 	0.702831225622904
16723903	4166	mysql - how do i aggregate by week and select the first day of the week?	select str_to_date(concat(year(fulfilled_at),      weekofyear(fulfilled_at),' monday'), '%x%v %w') from purchases 	0
16733284	38575	usage of group by and min with hsqldb	select p.id, p.expire_date, p.customer_id from product p    join (        select customer_id, min(expire_date) min_expire_date        from product        group by customer_id    ) p2 on p.customer_id = p2.customer_id         and p.expire_date = p2.min_expire_date 	0.204259727391587
16738074	24364	teradata sql query	select name      , grp      , min(startdt)      , max(enddt)   from (         select t.*              , sum(keepwithnext)                     over (partition by  name                               order by startdt                           rows unbounded preceding                         ) as grp           from (                  select t.*                       , case when t2.name is null                                then 0                                else 1                           end   as keepwithnext                    from t as t                    left outer                     join t as t2                      on     t.name  = t2.name                          and t.enddt = t2.startdt - 1                  ) as t         ) as t group by name, grp; 	0.745722466801325
16754899	37817	adding values of two columns in different databases sql	select coalesce(asum, 0) + coalesce(bsum, 0)  from (select sum(qty) as asum from dba.product) a cross join      (select sum(quantity) as bsum from dbb.stock) b 	0
16760871	7548	get highest ids in by an inner join and max id	select conversations.*, m1.*  from conversations  left join messages m1     on conversations.id = m1.cid          and m1.id = (             select max(m2.id)              from messages m2              where m2.cid = conversations.id         ) 	0
16788640	29756	mysql group by on two columns	select a.datetime, a.value, a.id from test a where not exists   (      select 1 from test b       where b.id < a.id        and (a.datetime = b.datetime or b.value = a.value)   ) 	0.00485561632604874
16790731	26035	how to add a column to sql result from other row in same table	select t1.num, t1.value, t1.info, t2.info as t2_info from yt t1 left join yt t2   on t1.num = t2.num   and t1.value <> t2.value where t1.value = 'a'; 	0
16804734	22877	getting list of records with no related records mysql	select `id`, `name` from `team`    where `id` not in (select distinct(`team_id`) from `games`)    and `state` = 'tx'; 	0
16805587	3591	get duplicate value on inner join statment on sql server	select distinct a.inquiryaccount         ,a.inquiryamount         ,a.inquirycustname         ,a.inquirylang         ,b.payamountpaid         ,b.payscreentext         ,b.payreceipttext         ,c.revrefno  from dbo.inquiry a  join dbo.payment b on a.inquiryaccount = b.payaccount  join dbo.reversal c on a.inquiryaccount = c.revaccount order by c.revrefno desc 	0.0237758125971891
16809788	24248	more than one row returned by a subquery used as an expression postgresql	select  a.stxid,  a.stxuserid,  x.sumamountstx,  s.userid,  s.amountsrc from  (select stxid, stxuserid from stx group by stxid, stxuserid) a  join (select stxid, sum(amountstx) sumamountstx from stxitem group by stxid) x using (stxid)  join credit using (stxid)  left join srcitem s on (a.stxid = s.souceid) 	0.123812333793016
16824590	30105	relational algebra: select only last try	select player_name,player_lastname,try,score from  (select player_name,player_lastname,try,score,rank() over (partition by player_name, player_lastname order by try desc)as try_rank        from score        )sub where try_rank = 1 	0.00685022282021083
16825154	23168	using an array in a php mysql where clause	select distinct user_id, fname, lname, profile_pic, school from users where user_id in      (select distinct user_id from interests     where interest like %{search_term}%) 	0.783958704678827
16845521	24936	sql server integer list table type null to return all	select * from #mytable   where a in (select n from @listvalues)   or (select count(*) from @listvalues) = 0 	0.000969288070555617
16851248	28419	query sqlce database with array	select * from articles where artname in ('name1', 'name2', 'name3') 	0.341948192524463
16854110	18836	subquery to join column's in same table?	select    orderlead.id as orderleadid,   leaddetail.name as lead_name,   concat(ifnull(c1.id,''), if(c2.id is null,'', concat(',',c2.name)), if(c3.id is null,'', concat(',',c3.name))) as lead_pref_country,   orderlead.time as orderlead_time from orderlead   inner join leaddetail on leaddetail.id=orderlead.lead   left join country as c1 on c1.id=leaddetail.pref_country_1   left join country as c2 on c2.id=leaddetail.pref_country_2   left join country as c3 on c3.id=leaddetail.pref_country_3 	0.00928984207008948
16867286	28619	sql where in but match all	select id from yourtable where genre in ('rock', 'popular', 'classical') group by id having count(distinct genre) = 3 	0.0296779453753925
16868758	2935	restrict many - many results in sql join	select    case when row_number = 1 then a_id end as a_id,   case when row_number = 1 then b_id end as b_id,   c_id from (   select      a.a_id,      b.b_id,      c.c_id,      row_number() over (partition by a.a_id, b.b_id order by c.c_id) as row_number,      row_number() over (partition by c.c_id order by c.c_id) as row_number2            from     table_a  a     join     table_b  b on a.a_id = b.a_id     join table_c  c on b.b_id = c.b_id   )  innerquery where    row_number2 = 1  	0.508426850885876
16878742	34433	mysql - multi-table select	select p.product_names     from products_description p, products_to_categories pc, categories_description c     where p.products_id = pc.products_id      and pc.categories_id = c.categories_id      and c.categories_name = "refurbished" 	0.674439664673128
16890132	40547	divide two sum of two interval	select t.*,(sum(case when row<=12 then index else 0 end)/ sum(case when row>12 then index else 0 end)) as result from ( select row_number() over(order by [year] desc,[month] desc) as row,[year], [month], pcode_9, [index]  from tbl08 where pcode = @code and (([year] * 12 + [month]) <= @currentyearmonth) and (([year] * 12 + [month]) >= @fcurrentyearmonth) and row > 12   < order by [year] desc,[month] desc ) t 	0.000342148665562756
16904649	7474	query to see if subscription is active between two date ranges	select * from yourtable where addressstartdate >= '1000-05-01'  and addressenddate <= '1000-05-30' 	0.000220434566107766
16909786	23357	mysql limit 1 get random (1,8)	select * from     (select * from tablename order by columnname limit 0,7) as derivedtablename     order by rand() limit 0 , 1; 	0.00910448490518423
16936135	31597	postgresql, select from max id	select my_id, col2, col3  from mytable  order by my_id desc  limit 1 	0.00240695401641493
16939849	20623	selecting rows on specific level with sql	select l3.* from region l1, region l2, region l3 where l1.upperid = 0 and l2.upperid = l1.id and l3.upperid = l2.id 	0.00217943340998968
16940580	10645	php pdo how do i show who i am following beside my list of users?	select u.id, u.username, if(f.follower_id is null, 0, 1) as following from users u left join following f   on u.id = f.user_id   and f.follower_id = $loggedinuser 	0.0186144085346963
16941757	34728	mssql exclude primary key in group by	select   col1 ,col2 ,col3 ,col4 ,count(*) over(partition by pat07, pat08, pat18) as totalperperson ,(select top 1 id from table1 where {criteria relating data to id}) as id  from table1  group by   col1 ,col2 ,col3 ,col4 	0.0132643785251286
16945881	16926	get records with more than one value and at least one of them is zero	select keyword,count(distinct id) from #tbl group by keyword having count(distinct id)>1 and min(id) = 0 	0
16946043	7354	group mysql rows by month and count data until each month	select month, count, @total:=@total+count as total from (select @total:=0) t straight_join   (select date_format(from_unixtime(timestamp), '%e %b %y') as month, count(*) as count   from results group by extract(year_month from from_unixtime(timestamp))) as m; + | month      | count | total | + | 1 jun 2013 |     3 |     3 | | 1 jul 2013 |     5 |     8 | | 1 aug 2013 |     7 |    15 | + 	0
16947943	4576	how to get the count of different categories from mysql database with php	select count(*) as cat_count, category from table_name group by category 	0
16970601	25808	mysql matches uuid against the primary key	select * from users where cast(users.id as char) = '4bde3afe-ce30-11e2-9e98-b27639b9f5a0' 	0.00977348835922355
16977301	6691	new to mysql relationships	select * from users  u , permissions  p  where u.permission_id = p.p_id; 	0.0751821447157861
16982368	16630	php sql request - query 2 tables, for results on one query	select * from table1 as t1 left join table2 as t2 on t1.car_id = t2.car_id where t2.user_id = $user_id 	0.0202914853609633
16982570	39117	negate regex pattern in mysql	select * from table     where column_name regex '[pattern]' = 0 	0.697821274696806
17009438	20324	show dates between now and 4 weeks later	select * from courses  where open='1' and date between curdate() and curdate() + interval 4 week  order by date, time 	0
17031413	7992	mysql find if other row(s) exist in the same table with the same value	select attendance from events natural join (   select   venue_id, event_date   from     events   group by venue_id, event_date   having   count(*) > 1 ) t where promoter_id = 5 	0
17032039	31067	combining sql queries	select q1.sendername      , q1.recievername      , q2."company name" ( select t_sendertable.namefull as "sendername", t_recievertable.recievername as "recievername"       , t_sendertable.id from ((dbo.t_sendertable as t_sendertable      inner join t_sendertable as t_sendertable on (t_sendertable.kd = maptable.senderid))      inner join t_recievertable as t_recievertabler on (recievertable.id = maptable.recieverid ) ) q1 inner join ( select t_license as "license", t_coname as "company name"       , t_license.senderid from (dbo.t_license as t_license      inner join dbo. t_coname on ( t_coname.id = t_license.senderid )) where (   t_license.check < '2' ) ) q2   on q1.id = q2.senderid 	0.340491632869259
17032424	14269	sql get the sum of entries from join tables	select     id     ,sum(table1.likes)     ,sum(table2.likes)     ,sum(table3.likes) from maintable left join table1 on maintable.id = table1.id left join table2 on maintable.id = table2.id left join table3 on maintable.id = table3.id group by maintable.id select     id     ,sum(table1.likes)+sum(table2.likes)+sum(table3.likes) from maintable left join table1 on maintable.id = table1.id left join table2 on maintable.id = table2.id left join table3 on maintable.id = table3.id group by maintable.id 	0
17054868	26133	how to pick a value that exists only between range of data entries?	select event  from mytable where date(`date`) <= '1980-01-14' order by `date` desc limit 1; 	0
17057943	29088	insert into a table values from another table using oracle	select id, sum(u_id*(if no = 1 then 1 else 0 endif)) as one, sum(u_id*(if no = 2 then 1 else 0 endif)) as two, sum(u_id*(if no = 3 then 1 else 0 endif)) as three, sum(u_id*(if no = 4 then 1 else 0 endif)) as four, sum(u_id*(if no = 5 then 1 else 0 endif)) as five, sum(u_id*(if no = 6 then 1 else 0 endif)) as six, sum(u_id*(if no = 7 then 1 else 0 endif)) as seven, sum(u_id*(if no = 8 then 1 else 0 endif)) as eight, sum(u_id*(if no = 9 then 1 else 0 endif)) as nine, sum(u_id*(if no = 10 then 1 else 0 endif)) as ten from table_1 group by id; 	0
17073231	39113	codeigniter - order my 'posts' by month?	select  `year`,`month`,(select count(id) from `posts` where `month` =p.`month`) as c from `posts` p  group by p.`month` order by `month` function getnews(){  $data = array();  $q = $this->db->query('select `year`,`month`,(select count(id) from `posts` where `month`=p.`month`) as c from `posts` p  group by p.`month`order by `month`');  if ($q->num_rows() > 0){    foreach ($q->result_array() as $row){      $data[] = $row;    } } $q->free_result();   return $data; } 	0.00831475418610842
17087069	39562	oracle sql: hierarchical query to generate specific sequence	select  r || l2, l || l2 from (         select to_char(rownum, '009') r, to_char(l, '009') l         from         (                 select l                 from                 (                     select  level as l                     from    dual                     connect by level < 1000                 )                 order by dbms_random.value         ) ) cross join (         select  level -1 as l2         from    dual         connect by level < 11 ) order   by         1, 2; 	0.191467663157959
17089033	40109	value is type of a and b	select distinct maker from      (select distinct model,speed from pc where ram=(select min(ram) from pc)) as lowestram  inner join product         on product.model=lowestram.model and  lowestram.speed=(select max(speed) from pc where ram=(select min(ram) from pc))  group by maker having maker in( select distinct maker from product where type='printer') 	0.0030835397448265
17091157	24144	sorting and ordering by two columns	select t.proj, t.release, t.releasedt from (select t.*, min(releasedt) over (partition by proj) as minrdt       from t      ) t order by t.minrdt, t.proj, t.releasedt 	0.0111262147571359
17093787	12808	sql- selecting columns based on date and batch number	select  * from(      select nsfield1 as datacolumnnamesame1,nsfield2 as datacolumnnamesame2 from sametable as ns where ns.batch='111111' and rundate between '1/14/13' and '1/16/13'  union all     select osfield1 as datacolumnnamesame1,osfield2 as datacolumnnamesame2 from sametable as ns where os.batch='111111' and rundate between '1/14/13' and '1/16/13'  ) as data  	0
17096247	25711	mysql check userid of last x posts	select       sum(if(userid = '$user_id',1,0)) = 5       from (          select userid from chat order by id desc limit 5      ); 	0
17096452	28139	select rows from sqlite which contains given values	select *  from tbl  where (    col like :param1 || ",%"    or col like "%, " || :param1    or col like "%, " || :param1 || ",%"    or col = :param1 ) and (    col like :param2 || ",%"    or col like "%, " || :param2    or col like "%, " || :param2 || ",%"    or col = :param2 ) 	0
17102457	8284	use of contains() in sql server	select * from product where contains(name,'"*1340*"'); 	0.299827312973058
17102808	26351	search in two mysql tables with non identical tables (keyword search)	select * from table1,table2  where table1.col1=table2.htnon and table1.col1 = "07731a0328" 	0.0145863676803043
17108015	30305	join two dataset in one ssrs chart report	select  u.firstname as username, count(i.id) as totalid, nullif(sum(case when i.resolveddate > i. resolvedbydate then 1 else 0 end ),0) as breached 	0.0452735126070371
17109792	7996	calculate the average difference between two date columns for multiple rows	select avg(datediff(view_date, sent_date)) from mails 	0
17109957	15075	jpql query manytoone	select c from childentity c where c.childid != (     select p.childentityref.childid from parententity p where p.parentid = :parentid) 	0.797320844653687
17132463	22013	messaging mysql table query	select *  from   table where  user2_id = some_id     and (start = 1  or to_user2 = 1 or (to_user2 = 0 and start = 0)) 	0.67404099387233
17136188	9933	oracle: first occurrence of a particular character in a string	select name,          instr(name, 'c')     from departments 	5.30174098135184e-05
17138657	20260	sqllite query a range based on column value	select * from prefix where 't6c' between substr(prefix, 1, 3) and substr(prefix, -3, 3) 	4.67357687555144e-05
17146807	9731	select value from combobox and display it's details in textbox	select product_id, p.category_id, product_name, product_cost, product_price, category_name  from product p  inner join category c on p.category_id = c.category_id 	0
17147500	27622	mysql sort category according to parent id	select   name,   case when parent_id = 0 then id else parent_id end as sort from   cars order by   sort,   id 	0
17148271	14722	last record query in two linked tables	select vendor, price from purchases p inner join purchasedetails pd on pd.purchaseid=p.purchaseid where purchaseid = (select top 1 purchaseid from purchases where detailid = detailid order by purchasedate desc) 	6.44271191859186e-05
17163779	21808	query to select & check 1 row at a time & stop when it finds the right value (mysql)?	select col1, col2 from (select col1,         col2,         if(col2 in (1,3) and @row = 1,@row:=@row+1, @row) as end,        if(col1 = 85 and @row = 0,@row:=1,@row) as start          from table1   join (select @row := 0 from dual) dummy) as magic where end = 1; 	0.00134757295603282
17167078	32922	sql query for unique record on basis of status	select max(id) as id, mobileno,        (case when sum(status = 'success') > 0 then 'success' else 'fail' end) as status from inglogs group by mobileno 	8.71065370722273e-05
17172255	10588	get top 10 records from db and record from current log in user	select *      from mytable    where rank <= 10    limit 10 union   select *     from mytable    where name = 'lll'  order by rank; 	0
17176917	24697	select promotional price	select min(case when `product_promotional_price` = 0 then `product_original_price`                 else least(`product_promotional_price`, `product_original_price`)            end) 	0.0378752866288029
17179459	39163	`order by` and `limit` combined with `join`	select *, films.category as filmcategory from (select *       from films       order by ref asc       limit 4) films left outer join items on items.`unique` = films.ref order by `unique` asc 	0.57358234796745
17185237	13230	select with when and sum	select sum(case              when (home_team = 'tupesy') then                home_goals              else                 away_goals             end)   from match  where (id_match = '1') 	0.278182173857845
17186665	36050	select in sql with specific format of date	select date from currencies  where date = convert(datetime, '11/06/2013 00:00:00', 103) 	0.00450612772679763
17187008	30115	pivot table with duplicate column key	select * from(     select customerid,r_id,phonenumber from (         select * ,row_number() over (partition by customerid order by preference) as r_id         from phonenumber ) as a where r_id<=3     )as p pivot(     max(phonenumber) for r_id in ([1],[2],[3]) )as pvt 	0.0055759843637057
17212842	31407	multiple table query - sql	select products.category, products.description, products.brand, stores.brands, stores.location, products_stores.price from products_stores inner join stores on stores.id = products_stores.stores_id inner join products on products.id = products_stores.products_id 	0.179459418368467
17226668	25721	is there a way to find a last substring?	select substring_index(     substring_index('yourstring', '"', -2), '"', 1); 	0.00147779480368121
17231324	40265	an sql statement to select the closest values	select * from a where b = 10 union  select * from a where b = (select max(b) from a where b < 10) union select * from a where b = (select min(b) from a where b > 10); 	0.0235169137188
17233280	15661	mysql query concatenating more than 1 related table	select t.*, group_concat(distinct p1.value), group_concat(distinct p2.value)  from table1 t      left join property_1 p1 on p1.table1=t.id      left join property_2 p2 on p2.table1=t.id  where t.id in (1,4)  group by t.id; 	0.00662809384962168
17239323	40863	oracle sql put values of a column in one row	select id,   number,   listagg(letter, ', ') within group(order by id, number) as letter from yourtable group by id, number; 	0
17244341	20063	select only where relational row is found	select distinct m.id, m.name, m.description  from  menu_categories m  join dishes d  on d.menu_id = m .id 	0.0116858438921727
17250294	25086	obtain the next times (in varchar) from the db in php, according to time now	select * from <yourtable> where time_start > now() 	0
17255758	39132	mysql query, two tables joining and using	select e.name, e.employeeid, count(a.articleid) from employees e left outer join articles a on a.employeeid = e.employeeid group by e.employeeid 	0.0447874448444449
17260802	6907	fill zeros for missing values in range	select   series, count(score.n) from   generate_series(0, (select max(n) from score)) series   left join score   on series=score.n group by   series 	0.000433999971013321
17268184	6756	fetching multiple records from same table	select title,        max(case when language = 'en' then nid end) english_nid,         max(case when language = 'ar' then nid end) arabic_nid   from table1  group by title 	0
17270069	14980	mysql import to varchar field contains something i don't see	select hex(columnname) 	0.00440025318011408
17277152	6590	sqlite - select distinct of one column and get the others	select * from t group by code; 	0
17281186	1040	select all from table1 and all from table 2 where there is no matching row in table 1	select * from table1 union all select * from table2 where not exists (select * from table1                                         where table1.w = table2.w                                             and table1.f = table2.f                                             and table1.c = table2.c) 	0
17283840	35953	choose a value between two columns sql - vba in excel	select case when a >= b then a else b end as max_value from yourtablename 	0.00153734644986374
17287282	40130	mysql having statement returning no rows	select t.order_sequence, t.order_number, t.order_date, t.fifo_date_in, t.fifo_cost   from tmp t   inner join ( select order_sequence, order_number, order_date                      ,min(datediff(order_date,fifo_date_in)) as ddiff                  from tmp                  group by order_sequence, order_number, order_date               ) m          on (m.order_sequence = t.order_sequence              and m.order_number = t.order_number              and m.order_date = t.order_date              and datediff(t.order_date, t.fifo_date_in) = m.ddiff) 	0.172436251375197
17305252	29053	checking if each value is assigned a unique name	select name, count(distinct value) from table group by name having count(distinct value) > 1 	0
17312978	31092	sql query balance	select a.seq, a.fld_date,b.fld_date as next_row_date,          a.cbu_in,a.cbu_out,a.balance   from ( your query ) a left outer join (your query) b  on a.seq = b.seq-1 	0.576268088185112
17322365	14887	sql 'while' condition	select     dol.id,      dol.price,     dol.amount,      (select sum(amount) from public.dollars dol2 where dol2.price <= dol.price) as sum_amount from     public.dollars dol where    (select floor(sum(amount)) from public.dollars dol2 where dol2.price <= dol.price) <= 5 order by price asc; 	0.451417489431829
17323516	21064	qa sql tables against historical data	select 'error ' + cw.timeperiod + ' current week:' + cast(cw.number as varchar) + ' prev week:' + cast(pw.number as varchar) from [current week db].table cw  inner join [previous db].table pw on    cw.item=pw.item    and cw.timeperiod=pw.timeperiod    and cw.number=pw.number 	0.109416486318662
17325117	26626	how to join a select and a join select into a single query	select  a.user_id, a.meta_value, b.user_nicename, count(sc.quiz_id) as quizes from    edo_usermeta a          left join edo_users b              on a.user_id = b.id         left join edo_plugin_slickquiz_scores sc             on sc.usr = b.id             and sc.usr_practice = 123456  where   a.meta_key = 'user_practice_role' group by a.user_id, a.meta_value, b.user_nicename; 	0.0127562328990542
17337844	5027	sql find char in data	select phone_number from table where  phone_number like '%[a-z]%' 	0.0221620236624024
17343919	33945	sql (sqlite) group by and count	select album, avg(rating) as avgrating from file  group by album  having sum(case when rating > 0 then 1 end)*1.0 / count(*) > 0.5 order by avgrating desc 	0.299228975659442
17344199	15347	combine two queries with count function for a single result set	select mv_date, sum(mv_count), sum(order_count), sum(order_revenue) from (     select dateopened as mv_date, 0 as mv_count, count(*) as order_count, sum(order_amount) as order_revenue     from bb_order     where (dateopened >= '2013-01-01' and dateopened <= '2013-06-30')     group by mv_date     union all     select dropoffdate as mv_date, count( * ) as mv_count, 0 as order_count, 0 as order_revenue     from bb_movement     where (dropoffdate >=  '2013-01-01' and dropoffdate <=  '2013-06-30')     group by mv_date     union  all     select pickupdate as mv_date, count( * ) as mv_count, 0 as order_count, 0 as order_revenue     from bb_movement     where (pickupdate >=  '2013-01-01' and pickupdate <=  '2013-06-30')     group by mv_date  ) mv group by mv_date order by mv_date 	0.00845069046337652
17349133	39882	join two tables only if the first contains certain values if not join another	select *  from tablea a  inner join tableb b on b.columns1 = a.column1     and isnumeric(a.column1) = 1 where 1=1 union select *  from tablea a  inner join tablec c on c.columns1 = a.column1     and isnumeric(a.column1) = 0 	0
17349675	9294	sql query for null, zero, and constant data	select  format(utctimestamp ,'yyyy-mm-dd hh:00:000 - yyyy-mm-dd hh:45:000 ')as hourtime ,         sum(case when elapsedvalue is null then 1                  else 0             end) as nodata ,         sum(case when elapsedvalue = 0 then 1                  else 0             end) as zerodata from    tbllive_trendlog_15min where   isnull(elapsedvalue, 0) = 0 group by format(utctimestamp ,'yyyy-mm-dd hh:00:000 - yyyy-mm-dd hh:45:000 ') 	0.165537783065941
17350508	16984	select top 1 from a group by and order by in a query	select id, field_name,  change_date,  prev_value,  current_value from (select *,  row_number() over (partition by field_name order by change_date desc) as  ranker from table )z where ranker = 1 	0.0039497796710812
17352133	23400	grouping columns into rows sql	select ps_product_lang.name, group_concat(ps_feature_lang.name) as feature, ps_feature_value_lang.value from ps_product left join ps_product_lang on ps_product_lang.id_product = ps_product.id_product left join ps_feature_product on ps_feature_product.id_product = ps_product.id_product left join ps_feature_lang on ps_feature_lang.id_feature = ps_feature_product.id_feature left join ps_feature_value_lang on ps_feature_value_lang.id_feature_value = ps_feature_product.id_feature_value group by ps_product_lang.name 	0.000901351203228963
17357608	27504	how to most efficiently select a row/record matching user id for many user ids?	select * from recordtable where userid in $user_id_array 	0
17361240	21859	replace second value if count is greater than one	select id,  if(name = @prev, 'xyz', name) as name, value , @prev:=name from a , (select @prev:=null) var order by id 	0.000102522994700607
17361387	28899	sql grouping by on a range of year	select  count(*),(convert(varchar,min(year(orderdate)))+'-' + convert(varchar,max(year(orderdate)))) as yearrange from orders group by floor(year(orderdate) /5) 	0.000241780246599608
17361899	34198	sql - select row only if column is equal with the current time	select * from table_name where str_to_date(column_b, '%y-%m-%d %h:%i') = str_to_date(now(), '%y-%m-%d %h:%i') 	0
17364907	19568	count highest no of conversation between two clients	select   least(emailfrom, emailto) email1,   greatest(emailfrom, emailto) email2,   count(*) from   yourtable group by   least(emailfrom, emailto),   greatest(emailfrom, emailto) order by   count(*) desc limit 1 	0
17370205	35021	selecting a subset of rows with mysql: conditionally limiting number of entries selected	select a.* from $marketdb a inner join (     select  seller, max(amount) amount     from    $marketdb     where   price=$minprice     group   by seller )  b on a.seller = b.seller and a.amount = b.amount group by a.seller; 	0
17382470	32888	still produce result from multiple inner joins if one join fails	select   ... from comments as c   inner join accounts as a   on c.account_id=a.account_id   left join ratings as r   on r.baker_id=a.account_id 	0.553084787601445
17383814	37881	how to search partial/masked strings?	select *  from user  where ssn in ('12312####',                '#23121###',                '##31212##',                '###12123#',                '####21234'); 	0.170106885994122
17385923	21839	sql server convert datetime to varchar with hyphens as separators	select replace(replace(replace(replace(         convert(nvarchar(30), getdate(), 110) + ' ' +         convert(nvarchar(30), getdate(), 14),         '-', '_'),         ' ', '_'),         ':', '_'),         '.', '_') 	0.492377963310607
17387378	32855	php order by another table with added count	select p.*, v.*, count(v.photoid) as nb_views from photos p, views v where p.unqid = v.photoid group by v.photoid order by nb_views 	0.00530993086804051
17407846	16284	select distinct value from one column, using another for ordering	select [name], max([score]) from t1 group by [name] 	0
17408680	20425	select all rows where a row does not have a value	select      topic_id  from      topic_table where      topic != 'client additions' 	0.000138440185789935
17412285	14657	sql server 2012 - running total	select * from (select id,        somedate,        somevalue,        sum(somevalue) over(order by somedate) as runningtotal       from testtable       )sub where somedate > '2009-02-20' 	0.304570766129411
17417102	3812	query that returns list of all stored procedures in a sql server database which have varchar as a parameter	select r.routine_name, p.parameter_name from    information_schema.routines r inner join information_schema.parameters p     on r.specific_catalog = p.specific_catalog     and r.specific_schema = p.specific_schema     and r.specific_name = p.specific_name where    p.data_type = 'varchar' 	0.00108732263985674
17423547	40233	select top dates grouped by id's	select userid, testid, max(somedate) from @tmp group by testid,userid; 	0
17427966	24019	psycopg2 - return first 1000 results and randomly pick one	select field1 from table1 order by id limit 1000; 	0
17437616	38438	mysql - sum from another table	select account_name, sum(balance) balance  from tblaccounts a left join tblinvoices i    on a.account_id = i.tblaccount_account_id where a.customer_id = 1 group by account_id 	0.00094854051004382
17444884	126	how to add time to datetime in sql	select dateadd(day, datediff(day, 0, getdate()), '03:30:00') 	0.0111248373832073
17462932	13777	data in a single record	select  col1,  col2,  col3,  col4,  col5, max(isnull(col6,0)), max(isnull(col7,0)), max(isnull(col8,0)), max(isnull(col9,0)) from table1 group by col1, col2, col3, col4, col5 	0.0019797208815191
17469943	19716	mysql query how to show opposite results	select    *  from    maintenance where id not in (select                    id                  from                    maintenance                  where                    from_date <= date_add(now(), interval 5 day)                    and to_date >= date(now())                  ) order by     from_date asc 	0.0696119014002061
17477136	33971	how to sum total amount for every month in a year?	select id, month(date) as "month", sum(amount) as totalamount from t where year(date) = 2013 group by id, month(date) 	0
17483556	2293	getting exact match record from a table	select *     from trial_category     where category_id in (260, 2880)    and trial_id not in (select trial_id                           from trial_category                           where category_id not in (260, 2880)) 	7.82784132320711e-05
17492783	38262	how do i return ids for which only a single record is returned in sql?	select id,         client_name,         client_manager from table_name where id in  (     select id      from table_name     group by id     having count(*) = 1 ) 	0
17492942	24095	select random rows, then sort by column from a different table	select *  from (   select      event_id,      data_id    from      events    where      category_id = 1    order by rand()    limit 5) c    inner join data d on d.data_id = c.data_id order by    d.creation_date; 	0
17506960	6131	how to select inverse of query	select     *  from      services where not exists( select     userservices.serviceid from     userservices where     userservices.serviceid = services.id  and     userservices.userid = '".$user."' ) 	0.125602458092757
17522685	35864	multiple column search for same value	select    if(sum(1s) > 0, 1, 0),    if(sum(2s) > 0, 1, 0),    if(sum(3s) > 0, 1, 0),    if(sum(4s) > 0, 1, 0) from `show` 	0.00135786541046207
17527403	18983	null value in my table	select 'insert into agency (agency_id) values (' + isnull(cast(agency_id as varchar(10)), 'null') + ')'    from user  where user_id = 1 	0.0684093163088052
17531618	35450	count occurrences of sets	select a,         b,         c = count(*)               over (                 partition by a, b)  from   yourtable; 	0.00251269679166483
17539793	23318	sql find distinct and show other columns	select *  from      mytable as t1,      (select deviceid, max(dateandtime) as mx from mytable group by deviceid) as t2  where      t1.deviceid  = t2.deviceid and      t1.dateandtime = t2.mx 	6.37879416375335e-05
17542366	40380	group by two columns and count	select count(*), created_at from order group by payment_option_id, created_at 	0.00390340948516996
17548742	29987	merge two tables in one	select    bv.`view_date`,   sum(bv.`view_total`) as view_total,   sum(bc.`click_total`) as click_total, from   tarlo.`tarlo_banners_views` bv, tarlo.`tarlo_banners_clicks` bc where bv.`banner_id` = 469 and bc.`banner_id` = bv.`banner_id` and bc.`click_date` = bv.`view_date` group by bv.`banner_id` order by bv.`view_date` asc ; 	0.00065478178162797
17554696	41287	order the output of multiple selects in sql	select t.team ,sum(amt) as teamtotal from tracker w  join teams t      on w.username = t.name  where w.activity = '2' and (isnumeric(t.team) = 1 and cast(t.team as int) between 1 and 10) group by t.team  order by teamtotal desc 	0.110177175052217
17565582	10991	check availability of selected room in date range	select * from `reservations` where $todate between date_from and date_to          or date_to between  $fromdate  and  $todate           or  $fromdate between date_from and date_to          or date_from between $fromdate  and $todate         and `obj_id` = $obj; 	0.000453519097323166
17582006	16425	parse varchar2 to table (oracle)	select regexp_substr(:txt, '[^,]+', 1, level)    from dual  connect by regexp_substr(:txt, '[^,]+', 1, level) is not null 	0.18877174251551
17587469	17844	comparing two sql tables with different different fields	select * from virtuemart_orders t1  inner join virtuemart_orderstatus t2  on t1.order_status=t2.order_status_code 	0.000114082555318066
17599049	27571	columns to rows maintaining userid	select userid,'col1',col1 as 'value' from mytable union select userid,'col2',col2 from mytable union select userid,'col3',col3 from mytable union select userid,'col4',col4 from mytable 	0.00894460053462682
17605736	17079	sql: select values from a list of values in separate rows	select 'a'  union all  select 'b' 	0
17607521	8124	mysql return values from same table based on a scale id	select a.element_id, a.data_value  from skills as a, skills as b where a.element_id=b.element_id and b.onetasoc_code='11-1011.00' and b.scale_id='im' and a.onetsoc_code = '11-1011.00'  and a.scale_id = 'lv' order by b.data_value desc 	0
17614474	7492	order by result of a query / mysql subquery	select x.*     from       ( select *            from show_episode e           join shows s             on s.imdb_id = e.imdb_id_show            join show_episode_airdate a             on a.episode_id = e.episode_id            join show_moyenne m             on m.show_id = s.id           where season = 1             and episode = 1             and a.airdate < '2013-07-12'           order              by a.airdate desc           limit 10       ) x   order       by moyenne; 	0.371026820339957
17622826	28386	mysql join: multiple fields same name	select c.id      , c.date_created      , c.date_approved      , c.notes      , c.id_user_student      , c.id_user_exm      , c.id_user_eval      , s.name as student_name      , e.name as exm_name      , v.name as eval_name   from certificate c   left   join user s on s.id = c.id_user_student   left   join user e on e.id = c.id_user_exm   left   join user v on v.id = c.id_user_eval 	0.0082782819350038
17626791	2005	sorting on mysql by string and number	select name      from mytable  order by cast(substring(name,locate(' ',name)+1) as signed),           substring(name,-1); 	0.0120777926320577
17637140	33891	query a column where column value could be anything in an array	select * from [table]  where [column_name] in ('1','2','3','4') 	0.316355089160118
17640904	21197	how to select top records from a table not using top / rownum?	select * from (select t.*,         (select count(*)          from table1 c          where c.order_column <= t.order_column) top_n  from table1 t) sq where top_n <= 5 	6.14968491220515e-05
17648047	4936	how to filter max value records in sql query	select * from tab where avg<(select max(avg) from tab); 	0.00242872012480103
17649286	36995	select min date in sql	select plateno, ticketstatus, [date] from (select row_number() over (partition by plateno order by [date] asc) as [index],              plateno,              ticketstatus,              [date]        from yourtable) a where [index] = 1 	0.0550981758613053
17649669	2669	how to use 2 sums in 1 select statement?	select sum(price) as [total items]      , (select sum(cash) as [total cash] from stores) from items 	0.0707769043024103
17651903	14806	top 1 date foreach date	select numid,  dateupdate,  dtromp, idc.idfiliale  from idc inner join glob on glob .idint = idc.idint            inner join grat on glob.idatt = grat.idatt             inner join update on update.idaffiliate = idc.idaffiliate where numid = 9976666 and datediff(day,dateupdate,dtromp) = (                                          select                                          min(datediff(day,dateupdate,dtromp))                                          from idc ainner join glob b on a.idint = c.idint                                            inner join grat con b.idatt = c.idatt                                             inner join update d on d.idaffiliate = idc.idaffiliate                                          where numid = 9976666 and idc.idaffiliate = a.idaffiliate and grat.dtrompu = c.dtrompu and grat.dtrompu>dtdebvalidite                                       ) 	0.0110639771179456
17660001	40353	sqlite3: select top n records in a column	select * from tab1 order by field desc limit 10; 	0.000144248528318044
17684940	2576	select condition based on multiple rows	select patid from tablea where name in ('a', 'b') group by patid having count(distinct name) = 2; 	0.000369107546842254
17687965	6021	sql server rank on value range	select t.*,        sum(case when value >= 10 then 1 else 0 end) over               (partition by id order by date) as ranking from table t; 	0.00545887119516092
17693835	17109	find type of sql statement using php and no regex	select insert delete update merge (newcomer on the block) 	0.155152961061714
17698908	9706	how to set multiple ssis variables in sql task	select a = (select coalesce(max(logkey),0) as logkey from log), b = (select coalesce(max(headerkey),0) as hrkey from header) 	0.655054604235655
17699148	17136	sql joining to the same column id	select    m.name   ,a.groupname as 'groupone'   ,b.groupname as 'grouptwo' from   main m inner join   detail a      on m.groupone = a.group inner join   detail b      on m.grouptwo = b.group where   m.id = 1 	0.000238895339238246
17709239	27970	sql select string with keyword	select id from errors where errordescription ='select name like ''*a*'' returned 0 results' 	0.517047927482909
17718298	6739	mysql count and get maximum from table	select count(score) as counts, id_player    from fl_poll     where position = 'attacker'     group by id_player    order by count(score) desc    limit 1 	5.26715855918736e-05
17718416	17181	how to sort by text first and then text containing numbers	select *    from table1  order by cast(column1 as integer), column1 	0.000225663681895374
17718643	16986	sql server how to set a default value when the column is null	select case            when user_name is null then "default value"            else user_name         end   from table 	0.00747391651450438
17718744	2384	button with a limit of one click per hour	select count(*) as clicks_in_the_past_hour from table  where click_time >= now() - interval 1 hour 	0.000117666012688054
17734301	32864	sql join when dates codes are involved	select s.sale, s.promo_cd, p.attribute from tblsales s   inner join tblpromo p      on s.promo_cd=p.promo_cd      and s.date between p.active_dt and p.inactive_dt 	0.131909523187839
17740343	26687	how to check that certain datetime is in between the adjacent row dates?	select (select movement from user where date <= ? order by date) = 'static'    and (select movement from user where date <= ? order by date) = 'static'    and (select movement from user where date <= ? order by date) = 'static'    and (select movement from user where date <= ? order by date) = 'static'; 	0
17749830	6880	fulltext contains "and do"	select * from sys.fulltext_system_stopwords where language_id = 1033 	0.561778588421021
17753112	24869	displaying results and hiding duplicates	select distinct `promo_cat` from mobi where `something`  = 'something' 	0.075869645695355
17754155	14535	sql: get 2 rows from each category	select distinct c1.id, c2.category from mytable c1 join mytable c2 on c1.category = c2.category and c1.id <> c2.id group by c1.category, c2.id; 	0
17762828	20688	query on multiple tables?	select cmp.name, cmp.surname, cmc.name, cmp.birthdate, cmp.card_no, cmr.amateur    from cm_players cmp    inner join cm_clubs cmc on cmp.club_id = cmc.club_id   inner join cm_registrations cmr on cmp.player_id = cmr.player_id   where cmp.name like '%$name%'    and cmp.surname like '%$surname%'    and cmr.amateur = 0    order by cmp.player_id asc 	0.0879937732720219
17763127	12331	mysql like order bu exact match	select * from table1 where column like '%$search%'     order by case when column like '$search%'  then 1                   when column like '%$search%' then 2                   when column like '%$search'  then 3 end 	0.398899559074395
17771182	11662	select last 3 rows from database order by id asc	select * from (     select * from table order by id desc limit 3 ) sub order by id asc 	0
17772055	34945	sql join query - linking four tables	select `activities`.*, `admins`.`admin_role_id` from (`activities`) left join `admins` on `admins`.`activity_id`=`activities`.`id` and admins.member_id=27500     join (`transactions_items`     join `transactions` on `transactions`.`id` = `transactions_items`.`id`     join `products` on `products`.`id` = `transactions_items`.`product_id`) on `activities`.`id`=`products`.`activity_id` where `transactions`.`member_id` =  27500 and `activities`.`active` =  1 	0.0983910397841841
17780122	26910	how that a row exists with specific values in mysql	select exists(select * from tablename where productid=210) 	0.000443958829665749
17784336	2875	how to display a dynamically generated number php, mysql	select count(*) as `cnt` ... echo $variable['cnt']; 	0.000442845924101658
17804787	4083	how to write query to fetch last week records	select empcode,eventdate1 as eventdate,intime, case when outtime is null then 'n/a' else outtime end as outtime from     tms_hourcalc  where intime1 >= dateadd(dd,(datediff(dd,-1,getdate())/7)*7-7,-1)  and intime1 < dateadd(dd,((datediff(dd,-1,getdate())/7)*7),-1)  and empcode = @empcode group by empcode, intime,outtime, eventdate1,intime1      order by intime1; 	0
17815360	7108	select *, sum() with equation only returns one row	select    *, (sum(`q6`) / (`q1` * (`q1` + `q2` + `q3` + `q4` + `q5` + `q6`) / 6) * 100)    as percent  from table  where field2 = 'xxx'  group by id order by `percent` desc 	0.0027292503202059
17846741	23396	mysql select max number of rows in contiguous rows	select player_id, count(*) num_continuous_days   from (   select player_id, goals, date, if(goals = 0, @n := @n + 1, @n) g     from table1, (select @n := 0) n    order by player_id, date ) q  where goals > 0  group by player_id, g 	0
17850443	21090	mysql- how to change the rows into columns based on quarter column	select student_name,        standard,          'q1' quarter1,          min(case when quarter = 'q1' then subject end) subject1,          min(case when quarter = 'q1' then marks   end) marks1,          'q2' quarter2,          min(case when quarter = 'q2' then subject end) subject2,          min(case when quarter = 'q2' then marks   end) marks2,          'q3' quarter3,          min(case when quarter = 'q3' then subject end) subject3,          min(case when quarter = 'q3' then marks   end) marks3,          'q4' quarter4,          min(case when quarter = 'q4' then subject end) subject4,          min(case when quarter = 'q4' then marks   end) marks4   from table1  group by student_name, standard, subject 	0
17856614	36376	how to get records with date value of this year and later in ms sql	select * from order1 where order_date between dateadd(year, datediff(year, 0, getdate()), 0) and getdate() 	0
17858084	29874	select where sum less than value	select employee.id,        employee.name,        date,        sum(`hour`)  from timesheet_entry join employee on timesheet_entry.employeeid=employee.id group by timesheet_entry.employeeid,date having sum(`hour`)<$hrslimit 	0.0128753429690698
17860702	15204	sql server 2012 query multiple but not all column counts	select    projecttype,   count(*) as total,   team,   sum(case when projectstatus = 'rec' then 1 else 0 end) as 'rec',   sum(case when projectstatus = 'hold' then 1 else 0 end) as 'hold',   sum(case when projectstatus = 'some' then 1 else 0 end) as 'some' from   sites where   projectstatus in ('rec', 'hold', 'some') group by   projecttype,   team 	0.157783904625685
17864792	3802	count rows returned from a group by	select count(distinct user_id) from applications where approved = 0 	0.0010380967387035
17878451	40671	sql join that retrieves selected record and where clause	select d.id dept_id, d.managedby  from      tbldepartment d  where     d.id = 13 union select dm.id dept_id , dm.managedby from      tbldepartment d  inner      join tbldepartment dm  on  d.managedby = dm.id where      d.id = 13 	0.130679030082558
17878700	40284	oracle sql query for aggregation of data	select coalesce(name, 'tot') name,         sum(col1) col1,         sum(col2) col2,         sum(col1+col2) tot from mytable group by rollup(name) 	0.349855264923612
17889432	34716	how to select top n rows that sum to a certain amount?	select t1.amount  from mytable t1 left join mytable t2 on t1.amount > t2.amount group by t1.amount having coalesce(sum(t2.amount),0) < 7 	0
17898265	23227	mysql, max 3 values	select u.* from users u order by rank desc limit 3; 	0.018061227428379
17899622	10938	getting result even null on field	select * from customer as c left join customer_group as cg     on c.customer_group_id = cg.customer_group_id where c.customer_id = '10002' 	0.017259583546759
17909107	27001	sql pivot-like records arrangement	select id,        max(case when header = 'firstname' then value end) as firstname,        max(case when header = 'lastname' then value end) as lastname from t group by id; 	0.128995170997144
17915396	20746	mysql combining tables specific order	select id, sort_order from ( select `date`, null delta, id, (@a_count:=@a_count+1) sort_order   from articles a_main, (select @a_count:=-1) z   union all select a.`date`, f.delta, f.id, f.weighted_rn   from (     select (@x:=@x+1) rn, a.*     from articles a, (select @x:=-1) z     order by a.`date` desc   ) a join (     select (@y:=@y+1) rn, truncate((f.delta - @y - (1/@y)),2) as weighted_rn, f.id, f.delta, f.skip     from features f, (select @y:=-1) z     where f.skip <> 1     order by f.delta   ) f on a.rn = f.rn order by sort_order ) merge 	0.0214732006354721
17922407	33823	select single field multiple times with multiple criteria	select project     ,sum(case when activity = 'shearing' then [surface area] else 0 end) as totalshearing      ,sum(case when activity = 'bending' then [surface area] else 0 end) as totalbending     ,sum(case when activity = 'assembly' then [surface area] else 0 end) as totalassembly     ,sum(case when activity = 'pc' then [surface area] else 0 end) as totalpc     ,sum(case when activity = 'infill' then [surface area] else 0 end) as totalinfill where ([posting date] between @startdate and @enddate) from ple group by project 	0.000448993072087395
17926831	8952	returning narrowed down select based on associated table	select [theme].[name], [themetype].[type]  from [theme]  left outer join [themetype]  on [theme].[themetypeid] = [themetype].[pk_themetype] join producttheme pt on  pt.productid=themetype.productid where producttheme.productid = variable-paramater-here and producttheme.themeid = theme.pk_theme order by [themetype].[type] 	0.000468084788359096
17930163	18861	sql query counting appearances in multiple columns	select clicklink1 as page, 'clicklink1' as link, count(id) as count from mytable group by clicklink1 union select clicklink2 as page, 'clicklink2' as link, count(id) as count from mytable group by clicklink2 union select clicklink3 as page, 'clicklink3' as link, count(id) as count from mytable group by clicklink3 	0.0190980191624789
17943822	3892	how to select multiple same column in one column	select [id],[tname],     stuff((select ',' + cast(t2.[mname] as varchar(10))     from movie t2 where t1.[id] = t2.[tid]     for xml path('')),1,1,'') somecolumn from theatre t1 group by [id],[tname] 	7.04273097036007e-05
17947697	15018	getting rank by id in mysql	select id, marks, rank from (select id, marks,     @currank := if(@prevval=marks,@currank,@studentnumber) as rank,         @studentnumber := @studentnumber + 1 as studentnumber,    @prevval:=marks   from student,(select @currank :=0, @prevval:=null, @studentnumber:=1 ) r   order by marks  desc ) sq where id='001' 	0.0160616764981582
17949107	1253	'implicit' join based on schema's foreign keys?	select * from t1 natural join t2 	0.00229489389184908
17957298	10116	unique values for drop-down menu	select site, warehouse, row_number() over (partition by warehouse order by warehouse) as rownumfrom(select site, warehouse, row_number() over (partition by warehouseorder by warehouse) as rownumfrom table1) as twhere t.rownum = 1 	0.0201931368224624
18001368	36990	trying to retrieve information from table and compile in top 10 list	select t.movieid, sum(t.qty) as totalquantity from transaction t group by t.movieid order by sum(t.qty) desc limit 10 	0
18004081	688	getting filename count from multiple tables group by that file name	select filename,         sum(case when t = 28 then 1 else 0 end) t28count,        sum(case when t = 29 then 1 else 0 end) t29count,        sum(case when t = 30 then 1 else 0 end) t30count   from (   select 28 as t, filename     from t28    union all   select 29 as t, filename     from t29    union all   select 30 as t, filename     from t30 ) q  group by filename  order by filename 	0.000453822066196019
18009261	23723	sum the total time periods over a given day in mysql	select sum(time_to_sec(timediff(end_time, start_time)) / 60 / 15) total   from active_periods  where day = 'friday' 	0
18025142	9971	mysql select from two tables based on id from url	select  a.ime_tarife, b.price  from    tarife a         inner join telefoni_dodatak b             on a.id = b.tarifa_id  where   b.telefoni_id = 35 	0
18035918	35778	multiple column match across rows	select  t1.key from table1 t1 inner join table1 t2 on t1.key = t2.key  where t1.attribute = 'createdat' and t2.attribute = 'updatedat' and t1.value < t2.value 	0.000937683913083261
18039085	10825	sql counts based only one year	select tbl_shows.song_id,         tbl_songs.song_name,            count(tbl_shows.song_id) cnt,         mid(tbl_songs.song_name,1,35) short_name,         tbl_shows.show_date   from tbl_shows right join tbl_songs      on tbl_shows.song_id = tbl_songs.song_id    and tbl_shows.show_date between '2013-01-01' and '2013-12-31'  group by tbl_shows.song_id  order by count(tbl_shows.song_id) desc  limit 5 	0
18056782	13265	group each sections by points and competitionname descending order	select id,name,comp_desc,points  from ( select section,id,name, 'competion1' as comp_desc, c1points as points from students union select section,id,name, 'competion2' as comp_desc, c2points as points  from students union select section,id,name, 'competion3' as comp_desc, c3points as points  from students ) t where points <> 0 group by section, name,comp_desc, points order by  section, points desc, comp_desc desc; 	0.00106706936867599
18064870	2623	trying to get the max of a column in sql while referencing different tables	select c.date, people.name, people.age, c.gradterm from people inner join (select date, max(grad) [gradterm]             from ceremony             group by date) c     on people.grad = c.grad 	7.6525220627355e-05
18075592	14030	how to convert decimal to datetime in where clause	select * from clbaltrntbl where convert(datetime, convert(varchar(8), lstdat), 112) >= @sdt     and convert(datetime, convert(varchar(8), lstdat), 112) <= @edt 	0.221012258147843
18075822	41270	transpose of rows and columns using pivot in sql server	select '50kgbags' [bags], * from (select planttype  ,sum(noof50kgsbags*50)[50 kg] from       k_feedplantentryindent where  (date between '2013-04-01 00:00.000' and getdate()) and   (attrited = 'true') group by planttype)as t pivot ( sum([50 kg]) for[planttype] in( rohini,sneha,kjl,suguna ) ) as t2 	0.0071450475228321
18089001	15358	conditionally select from one table or another table	select     a.column2     , case when b.column2 is not null then max(b.column3) else a.column3 end     , a.column4 from     tablea a     left join tableb b         on a.column2 = b.column2 group by     a.column2     , a.column3     , a.column4     , b.column2 	5.49979095041498e-05
18109276	13304	select multiple columns into multiple variables	select t1.date1, t1.date2, t1.date3 into v_date1, v_date2, v_date3 from t1 where id='x'; 	0.0029513415427492
18114458	23523	fastest way to determine if record exists	select top 1 products.id from products where products.id = ?; 	0.0130827631696523
18115224	28954	how to select only few rows from a column in sql (sqlite database browser)?	select * from test           where rowid between                              (select rowid from test where words = 'xerox') + 1                       and                              (select rowid from test where words = 'stars') - 1  union all select ' union all select * from test          where rowid between                              (select rowid from test where words = 'pen')                      and                              (select rowid from test where words = 'apes'); 	6.01706722674378e-05
18122650	25107	how to split one large database table into multiple database tables	select * into... 	0
18135869	22422	select a column from a different table in sql server	select a.data1, b.data2 from a_table a join b_table b on a.data3 = b.data3 	0.00040501736758929
18136659	36590	get random record in a set of results	select * from <my_table>  order by rand() limit 4 	0.000102054862571729
18137790	34067	is there a way to select multiple rows and append one row of the most recent entry to this original query?	select  * from crm_main d outer apply         (         select top 1 timestamp, customerid         from crm_comments m         where m.customerid = d.id         order by                 m.timestamp desc         ) m; 	0
18142726	3932	order by time for sysdate	select to_char(date_id, 'dd/mm/yyyy hh24:mi:ss') as date_id from some_table tbl order by tbl.date_id desc; 	0.0556955813172882
18147996	12964	mysql between statement for string	select  * from tbl where  date('2013/07/01,s')  between @startdate and @enddate  ; 	0.195953594497494
18153671	28665	joining tables back to themselves in mysql	select     u.name as user_name,     m.name as maintainer_name,     l.name as location_name from user as u     left outer join document as d on d.id = u.doc     left outer join user as m on m.id = d.maintainer     left outer join location as l on l.id = u.loc 	0.126769534533958
18154723	16590	extract text between words	select a.*,        regexp_substr (a.tax_description,                       '\d+,?\d*',                       instr (a.tax_description, 'ipi')) ipi,        regexp_substr (a.tax_description,                       '\d+,?\d*',                       instr (a.tax_description, 'iva')) iva   from tax a; 	0.0119464490228702
18200009	41058	combine wins and losses in same row	select sum(case when (s.hometotalruns - s.awaytotalruns) > 0 and t2.teamname = 'pirates'                   then 1 else 0             end) as roadlosses,         sum(case when (s.hometotalruns - s.awaytotalruns) > 0 and t1.teamname = 'pirates'                  then 1 else 0             end) as homewins,         'pirates' as teamname  from scores s  inner join games g  on g.gameid=s.gameid  inner join teams t1  on t1.teamid=g.hometeam  inner join teams t2  on t2.teamid=g.awayteam  where 'pirates' in (t1.teamname, t2.teamname); 	0.00170165646152678
18205723	33879	select sum if null - update "0"	select isnull(sum(castka), 0) as sumcastka from kliplat 	0.11891118936196
18211137	31555	filter unique records from a database while removing double not-null values	select *  from yourtable t1 where z is not null     or not exists          (select * from yourtable  t2           where t2.id = t1.id and t2.z is not null) 	0.000155669340068141
18217035	20254	find out the employees who were absent for 3 consecutive days	select distinct a.employeename from attendance as a join attendance as b on b.leave_date = a.leave_date + 1 and b.employeename = a.employeename join attendance as c on c.leave_date = b.leave_date + 1 and c.employeename = b.employeename 	0
18225662	25570	find sum of points and grouping	select two.totalc1, one.totalc2, one.totalc3, one.totalone + two.totalc1 as totalall from  ( select school,   sum(c2points) as totalc2,   sum(c3points) as totalc3,   sum(c2points + c3points) as totalone from students group by school order by totalone desc) one left join (select school, sum(ma) as totalc1 from (select school, chess, max(grouppoint) as ma from students group by school, chess) as b group by school) two on one.school = two.school 	0.00358667555178423
18225906	40770	select a record from each group if it has given value in column otherwise any one record	select vendorid      , city from vendor outer apply (     select city = [text]     from mastervalues     where exists(         select count(*)         from vendordetail         where vendorid = vendor.vendorid             and detailcity = @givencityvalue             and value = detailcity     ) or vendor.city = value ) t 	0
18243366	10245	mysql: aggregate aggregated values	select      year(t.date) as y,      month(t.date) as m,      t.person_id as id,      count(*) as freq,     case when p.freq = 0 then 0          else (cast(count(*) as float) / p.freq) * 100           end as rate from table t join (     select          year(t.date) as y,          month(t.date) as m,           count(*) as freq     from table     group by y, m ) p on p.y = year (t.date) and p.m = month (t.date) where t.date between '2013-01-01' and '2013-06-30' group by y, m, id 	0.143675580868885
18246818	7858	how to calculate sum of two columns from two different tables without where clause?	select income, expense, income-expense balance from (select sum(rate) income       from _income) i join (select sum(rate) expense       from _expense) e 	0
18261024	814	select rows with the same field values	select a.* from table1 a join (select recordt, readloc       from table1       group by recordt, readloc       having count(*) > 1       )b on a.recordt = b.recordt  and a.readloc = b.readloc 	5.56334489362119e-05
18275151	31153	removing duplicates from sqldatasource	select distinct * from tb_chapter where c_courseid = '" + _courseid + "' " 	0.0561555641921325
18278805	22044	better way to detect the number of consecutive records for a lot of different unique user ids	select studentno, grp, attendancecode, count(*) as numinrow,        min(classdate) as datestart, max(classdate) as dateend from (select acm.*              (row_number() over (partition by studentno order by classdate) -               row_number() over (partition by studentno, attendancecode order by classdate)               ) as grp       from attendancecodemaster acm      ) acm group by studentno, grp, attendancecode; 	0
18303580	38148	get profile posts from friends	select      `f`.*,     `pp`.*,     `ai`.`name`,     `ai`.`lastname` from `friends` as `f` left join `profile_posts` as `pp`     on         `pp`.`posted_user_id` = `pp`.`user_id` and         `pp`.`user_id` = `f`.user1_id or         `pp`.`user_id` = `f`.user2_id left join `account_info` as `ai`     on `ai`.`u_id` = `pp`.`user_id` where     `pp`.`user_id` = `pp`.`posted_user_id` and     `f`.user1_id = 1 or     `f`.user2_id = 1 and     `pp`.`user_id` = `pp`.`posted_user_id` group by `pp`.post_id order by `pp`.date_posted desc limit 0,20; 	0
18316071	37120	compare sql result rows with each other	select id, value, comment, sort, store, price from (select t.*,              count(*) over (partition by value, comment, sort, store) as cnt       from t      ) t where cnt > 1; 	0
18333275	25326	is there a way to get sum of column whose datatype is varchar	select sum(convert(decimal(10,2), total)) from tbl_preorder         where emailid='xyz@email.com' 	0.000438605979018418
18334022	29686	query show result from relations where one of the value is 0	select fn.nome as fnome, m.nome as mnome, f.preco from  fornecido f left join fornecedor fn  on f.idfornecedor = fn.idfornecedor  left join modelo m on f.idmodelo =m.idmodelo  where f.codmaterial=8978998 	8.51358002336443e-05
18353250	34493	convert sql table to xml	select 'users' as [@name],         (select 'id'       as [@name], id       as '*' for xml path('column'), type),         (select 'username' as [@name], username as '*' for xml path('column'), type),         (select 'email'    as [@name], email    as '*' for xml path('column'), type) from users for xml path('table'), type 	0.0827996314273351
18362653	30523	concatenate many rows into a single text string with grouping	select distinct       fileid     , stuff((         select n', ' + cast([filename] as varchar(255))         from tblfile f2         where f1.fileid = f2.fileid          for xml path (''), type), 1, 2, '') as filenamestring from tblfile f1 	5.11904419318223e-05
18362850	1957	return results where a shared value is shared between two tables and the timestamp is different	select * from table1 as a inner join table2 as b on a.valuea = b.valuea where a.valueb > b.valueb 	0
18374707	37205	how to select and sum in single sql query	select (select sum(total) from `table`) totalsum, a.* from `table` a 	0.0371520382397666
18381765	11099	how to write multiple joins in mysql	select     questionnaire_status.*,     rep_list.last_name,         rep_list.first_name,     dept_codes.dept_name  from                     questionarrie_status left join     rep_list on        questionnaire_status.rr = rep_list.rr left join     dept_codes on     rep_list = dept_codes.dept_id left join     questionarrie_status where      questionnaire_status.attestation_submitted = '0' 	0.730552595508719
18400249	11629	how to select column in table by creating row in another table in mysql	select item_id, price,        (min(case when tax_name = 'vat' then tax end)) vat,        (min(case when tax_name = 'lbt' then tax end)) lbt,        coalesce(min(case when tax_name = 'vat' then tax end),0) +        coalesce(min(case when tax_name = 'lbt' then tax end),0) +        price total   from        (select a.item_id item_id,               c.tax_name tax_name,               (c.tax_value * b.price / 100) tax,               b.price price          from item_tax a inner join item_master b on a.item_id = b.item_id                          inner join tax_master c on a.tax_id = c.tax_id) as calc  group by item_id, price; 	7.55982483570373e-05
18402934	4211	how to check if selected date range is between another date range	select      * from     lifecycles where     str_to_date(life_start_date, '%m/%d/%y') <= '2014-01-01'      and str_to_date(life_end_date, '%m/%d/%y') >= '2013-08-01'; 	0
18404938	21347	mysql position in recordset	select *, @ctr := @ctr + 1 as rownumber from leaderboards, (select @ctr := 0) c order by time asc, percent desc 	0.0711998146149805
18412695	13331	inverse of inner join (intersect) with multiple foreign keys	select     `purchase`.`purchase_id`, `purchase`.`product_id` from `purchase`   left join `sale` on `sale`.`purchase_id` = `purchase`.`purchase_id` and `sale`.`product_id` = `purchase`.`product_id` where    `sale`.`sale_id` is null order by    `purchase`.`purchase_id`, `purchase`.`product_id` 	0.187050740710708
18414383	14805	how to add a where clause to a column from a correlated subquery	select * from ( select *, [status]=(select max([status]) from data_121emaillog o2  where o2.data_121id = o1.data_121id) from data_121 o1) a where a.[status] = 2 	0.239901293467662
18441115	2485	mysql max from sum	select id, max(reg_sum) from (    select id, sum(value) as reg_sum from table     where  (date between '2009-01-01' and '2009-03-01')    group by  id, reg ) a group by id 	0.0160841904733359
18447985	34790	using inner join and max(), to return same row as max	select yourfields (not all of them) from players p join matches m on m.pid = p.pid join (select pid, max(rating) maxrating from matches group by pid) temp  on p.pid = temp.pid and rating = maxrating etc 	0.00420136140290886
18466207	13830	is possible to count alias result on mysql	select    @a:=abs(40-90) as column1,    @b:=abs(50-10) as column2,    @c:=abs(100-40) as column3,    @a+@b+@c as columntotal; 	0.539301505852721
18469475	12014	php mysql table rows	select u.email,i.title,i.content,i.date,i.hits from user u,info i where u.id = i.id; 	0.0133008610264661
18471909	28249	having issues with start and end dates	select     clientid, session, sum(duration), min(timestamp) as timestamp_start, max   (timestamp) as timestamp_end from         dbo.tblhistory where     (timestamp >= dateadd(yy, - 1, getdate())) group by clientid, session 	0.1387898842094
18473010	18381	join table on one record but calculate field based on other rows in the join	select a.*,  case    when s.emailaddress is not null     then 1     else 0   end as incentiverecieved from abandoncart_subscribers a  left join (select distinct emailaddress            from sendlog s             where s.campaignid is null            and datediff(d,s.senddate,getdate()) <= 7            ) s on a.emailaddress = s.emailaddress  where datediff(day,a.dateabandoned,getdate()) <= 1 	0
18474323	36326	group by a month and display each month to corresponding value	select monthname(created_at) as month , sum(grand_total) as total from sales where created_at between '2012-01-01' and '2013-01-01' group by monthname(created_at) 	0
18492687	19655	return the record with the largest iteration	select t1.* from document t1 inner join      (select number, revision, max(iteration)      from document     group by number, revision) t2 on t1.number = t2.number and     and t1.revision = t2.revision and t1.iteration = t2.iteration 	0.00345596727577684
18494829	24683	selecting multiple max() values using a single sql statement - postgresql	select   max(case when data_type='world of warcraft' then value end) worldofwarcraft,   max(case when data_type='quake 3' then value end) quake3,   max(case when data_type='final fantasy' then value end) finalfantasy from yourtable; 	0.00449507050741058
18499136	27320	selecting row count from associated table without subselect	select u.id, u.email,     count(distinct(s.id)) as total_schools,     sum(points) as total_points from users u left join schools s     on u.id = s.user_id  group by u.id 	8.15789093952478e-05
18499157	15168	substring each row of a column in mysql	select substring(menu_name,1,position(substring_index(menu_name,'|',-1) in menu_name)-2) as menu from table_name; 	0
18512058	20596	mysql search string and numbers like #654	select * from table where field  rlike '#[0-9]{3,}' 	0.206160587775365
18514172	25333	how to select 10 random records for 3 items that all 3 items exist in the selection	select id,        store_id,        item_id,        product_id   from (select id,                store_id,                item_id,                product_id,                row_number ()                   over (partition by store_id order by r1, dbms_random.value)                   r2           from (select id,                        store_id,                        item_id,                        product_id,                        row_number ()                        over (partition by store_id, product_id                              order by dbms_random.value)                           r1                   from mytab))  where r2 <= 10; 	0
18539237	40392	mysql ordering by index id from separate table	select * from cs_products join cs_manufacturer on cs_product.manufacturer_id = cs_manufacturer.id order by cs_manufacturer.name 	0.0013206163064281
18543576	31349	oracle sequential field validation	select t.* from t where (t.field1 is null and coalesce(t.field2, t.field3, t.field4, t.field5) is not null) or       (t.field2 is null and coalesce(t.field3, t.field4, t.field5) is not null) or       (t.field3 is null and coalesce(t.field4, t.field5) is not null) or       (t.field4 is null and t.field5 is not null); 	0.137050532963951
18545426	12778	mysql joins and creating a new table(?)	select a.userid, b.username, a.contactid,         c.username, a.subject, a.message, a.timestamp  from feed as a, users as b , users as c where a.userid=b.userid and a.contactid=c.userid 	0.285939957752024
18547566	30084	store multiple values in a single cell instead of in different rows	select pid from table where find_in_set('us', available) 	0
18557121	5394	having clause or a select list, and the column being aggregated is an outer reference	select * from mbr_mst where mbr_join_dt = (select min(mbr_join_dt) from mbr_mst); select top 1 * from mbr_mst order by mbr_join_dt; 	0.645944708069757
18563126	4878	select max value with join	select f_name,         f_salary from (   select t_employee.f_name,           t_salary.f_salary,          dense_rank() over (order by t_salary.f_salary desc) as rnk   from t_salary       inner join t_employee on t_salary.f_employee_id=t_employee.f_id  ) t where rnk = 1; 	0.0644496235841343
18569810	5809	taking sum of column based on date range in t-sql	select sum(amount) sum_amount from <table> where voucherdt >= dateadd(month, datediff(month, 0, current_timestamp), 0) and voucherdt < dateadd(day, datediff(day, 0, current_timestamp), 1) 	0
18585979	10468	sql: parse comma-delimited string and use as join	select * from table1 t1 join table2 t2 on ','||t1.id||',' like '%,'||t2.id||',%' 	0.793048153618967
18594008	18101	how to get fields value from mysql function return	select   case lower(substr(dayname(now()),1,3))   when 'mon' then mon   when 'tue' then tue   ...   when 'sun' then sun   end as todaystime from mytable 	0.000287362053125904
18596874	36263	how to combine two simple sql queries	select p.avatar from person p join      person_magazine pm      on pm.person_id = p.id join      magazine m      on pm.magazine_id = m.id where p.newsletter = 1 and m.name = 'web designer' 	0.202042496137735
18601915	5231	mysql group by in a csv field	select colors.color, count(*) from   products inner join colors   on find_in_set(colors.color, replace(products.color, ' ', ''))>0 group by   colors.color 	0.0341425443867859
18607244	4824	mysql : how to know which table that record belongs to in union result	select some_column, 'union_1' as from_where from table1 union  select some_column, 'union_2' as from_where from table2 	0.000275061193902621
18609706	39559	transpose the resulted rows in oracle 9i	select      max(case when language_name = 'english' then uomt.description else null end)        as english_description,     max(case when language_name = 'german' then uomt.description else null end)        as german_description,     uomt.unit_of_measure_id from unit_of_measure_trans uomt inner join language l on (uomt.language_id = l.language_id) group by uomt.unit_of_measure_id order by uomt.unit_of_measure_id; 	0.0827632734013387
18613121	17021	mysql manually add id in clause "where in (select ...)"	select * from t1 where child_id in  (   select child_id from t2 where parent_id='1234'   union     select 5678 ) 	0.592692375126294
18620575	35072	split for xml path results into separate rows	select     125 as administratorid,     'bertha' as administratorname,     (         select             101 as teacherid, s.id, s.first, s.last         for xml path('student'), type     ) as xmlformat from dbo.students s 	0.00030967672458795
18623807	7656	find and count duplicate records in sql & order by maximum of count	select `items`.`item_name`, ifnull(count(`votes`.`item_id`),0) as `voting` from `votes` left outer join `items` on `items`.`item_id` = `votes`.`item_id` group by `items`.`item_id` order by `voting` desc; 	0
18635526	16873	changing the time format from hh:mm:ss to hh:mm am/pm	select time_format('10:20:00', '%h:%i %p') 	0.000168527882980199
18637937	15489	how to use outer-join with a where clause in an empty table	select * from filledtable  left outer join emptytable  on filledtable.id = emptytable.reffilledtableid and emptytable.value = 5 	0.687046737422831
18638219	38154	mysql - how to join table twice with the same table	select `main`.`id`,         `main`.`name`,         h.`name` as `hair_color`,         e.`name` as `eye_color` from `main` left join `items` h on `main`.`hair_color` = h.id left join `items` e on `main`.`eye_color` = e.id where `main`.`id` = 1 	0.00197748892224042
18641118	33952	teradata creating group id from rolling sum limit	select      prod_id ,   count(distinct prod_id) as qty ,   sum(qty) over (order by qty rows unbounded preceding) running ,   width_bucket(running, 1, 120*2000000, 120) as grp_nbr from tmp_work_db.prod_list group by 1 	0.00876225743086826
18654282	23110	query for returning the changes in the last month	select a.employee_id as crewcode,         a.emp_firstname,          emp_lastname,          b.base,          b.base_for as  'date'    from `hs_hr_employee` as a,         `employee_base_table` as b    where b.base_for=(select date_format(str_to_date( curdate( ) , '%y-%m-%d' ),'%m-%y'))      and a.emp_number=b.emp_number    group by a.employee_id 	9.21818118077253e-05
18672688	18633	fetching records of employee hired in specfic month	select ename, job from emp where to_char(hiredate, 'mon') = 'feb' 	0
18679426	4132	find pattern in some mysql row with php	select count(*) match_count from thetable t1 join thetable t2 on t1.id+1 = t2.id join thetable t3 on t1.id+2 = t3.id where t1.value = 1 and t2.value = 0 and t3.value = 1 	0.00692837971472168
18688743	12141	mysql count and count distinct in same query	select user_id,      job.job_id as job_id,     job_link,      count(job.click_ip) as click_ip,      count(distinct job.click_ip) as click_ip_distinct from user join job on user.job_id = job.job_id where user.user_id =7 group by job_id 	0.0115630978472155
18698114	29709	query multiple sql tables	select * from jos_vm_product    inner join <second product table> on jos_vm_product.product_id = <second product table>.product_id   inner join <third product table> on jos_vm_product.product_id = <third product table>.product_id order by jos_vm_product.product_publish desc 	0.217201663000197
18720310	19111	how to get records that exist in one mysql table and not another	select wafer_log.wafer, wafer_log.id as wlid  from wafer_log where wafer_log.id not in (select id from bt_log); 	0
18722749	36069	accessing parent query variables in sub query	select      s.id, sum_virality, ( ( (sum_likes) + ( sum_comments) ) * ( 1 / ( 1 +  s.created_at  / 3600000 ) ) )as response from spreads s inner join (select t.spread_id, date_format(t.created_at,'%y-%m-%d %h') created_date, sum(t.virality) sum_virality, sum(t.likes) sum_likes, sum(t.comments) sum_comments             from spreadstimeline t             where t.spread_id = s.id             group by created_date) as history group by     s.id 	0.414763259650772
18725168	5962	sql: group by minimum value in one field while selecting distinct rows	select mt.*,      from mytable mt inner join     (         select id, min(record_date) mindate         from mytable         group by id     ) t on mt.id = t.id and mt.record_date = t.mindate 	0
18745874	36111	sql, select if or select case	select    case when i_userkey = 1 then id else null end as id    case when i_userkey = 1 then gender else null end as gender   case when i_userkey = 1 then age else null end as age from tablea 	0.786136119323199
18751644	29218	select only records with duplicate (column a || column b) but different (column c) values	select first_name, last_name, count(distinct activity_id) from <table_name> group by first_name, last_name having count(distinct activity_id) > 0; 	0
18757098	8043	how to find tables where more than one column references the same table in postgresql	select     sc.relname,      dc.relname as ref_relname,     c.confkey from pg_catalog.pg_constraint as c      inner join pg_catalog.pg_class as sc on sc.oid = c.conrelid     inner join pg_catalog.pg_class as dc on dc.oid = c.confrelid where c.contype = 'f' group by sc.relname, dc.relname, c.confkey having count(*) > 1 	0
18771560	27213	mysql/php counting the top 3 most common values in a column	select tid, count(tid) as occurences  from table  group by tid  order by occurences desc  limit 4 	0
18773507	17741	select rows based on grouping in same table	select distinct id from table1 where id not in (   select id   from table1   where product in ('savings', 'chequing') ) 	0
18789278	14203	checking the capacity of a trip at register	select trip.id,trip.capacity,trip.morecolumns,count(*) as number_of_registrations from trip  join tripregisteration on trip.id=tripregisteration.tripid where registerationstate = "approved" group by trip.id,trip.capacity,trip.morecolumns having trip.capacity< number_of_registrations 	0.0229775507496512
18790566	19651	using limit in mysql to limit results based on column value (php/mysql)	select   p.id, guid, post_parent, post_title from ( select   a.id as id,   count(*) as rank from (   select id, post_parent   from $wpdb->posts   where post_type = 'attachment'     and post_mime_type like 'image/%'     and post_status = 'inherit'   ) as a join (   select id, post_parent   from $wpdb->posts   where post_type = 'attachment'     and post_mime_type like 'image/%'     and post_status = 'inherit'   ) as b on b.id <= a.id and b.post_parent = a.post_parent group by a.id ) as r join $wpdb->posts p on r.id = p.id and r.rank <= 3 where p.post_parent in (   select object_id from $term_relationships   where term_taxonomy_id = $post_term) group by p.id ; 	0.000391091355779754
18793135	2992	sql query: joins+condition+order	select * from (     select student.use_id, message.mes_create_at, message.from_use_id, message_user.to_use_id     from user student     join message on message.use_id = student.use_id and student.use_role = 1     join message_user on message_user.mes_id = message.mes_id     where message_user.to_use_id in (select use_id from user where use_role = 2)     union     select message_user.to_use_id, message.mes_create_at, message.from_use_id, message_user.to_use_id     from user teacher     join message on message.use_id = teacher.use_id and teacher.use_role = 2     join message_user on message_user.mes_id = message.mes_id     where message_user.to_use_id in (select use_id from user where use_role = 1) ) as temp order by mes_create_at desc 	0.563282522116172
18798137	10024	selecting distinct on where clause	select distinct    sb.company    ,b.id  as id    ,bds.id as pid    ,brp.bid from supp b left outer join sales bds on (bds.sid = b.id) left outer join tperiod brp on (brp.id = bds.rid) left outer join tbuyer sb on (sb.id = brp.bid) where  b.ownerid = @oid group by b.ownerid 	0.121908244507916
18799418	38909	combine 3query for s_p	select month(user_lastlogin) as month,        year(user_lastlogin) as year,        count(*) as 'total reg',        sum(case when user_regtype = 'lr' then 1 else 0 end) as 'lr reg',        sum(case when is null or user_regtype = 'bbr' then 1 else 0 end) as 'bbr reg'   from bb_user  group by month(user_lastlogin), year(user_lastlogin) order by year desc, month desc 	0.664808186039451
18799577	3664	sql server compact 4.0 select last datetime for each day	select max(timestamp) timestamp, filename   from table1  group by datepart(dd, timestamp), filename 	0
18800925	16323	item popularity in mysql	select items,        (select  count(distinct b.views)          from    tablename b         where   a.views <= b.views        ) as rank from    tablename a order   by views desc 	0.0319626069128049
18803841	28944	inserting xml in table	select     t.data.value('(weather/@location)[1]', 'nvarchar(max)') as location,     t.data.value('(weather/forecast/date)[1]', 'date') as date from table1 as t 	0.0634375331513867
18805784	15623	mysql search across multiple rows return distinct id	select a.project_list_id  from database.project_details a inner join database.project_details b on a.project_list_id = b.project_list_id where a.answer = '96720' and a.field_name = 'zip' and b.answer = 'hi' and b.field_name = 'state' 	0.000234804110770096
18805845	40325	mysql query where select produces an array	select sum(txnpnl) from tdmarketprob.pnl_transactions     where instrumentid in (select instrumentid     from tdmarketprob.pnl_instruments     where symbol="es") and txnpnl <>0; 	0.780546462013466
18806483	21401	sql join two tables	select pl.phone_name   ,pl.phone_price   ,pl.phone_price2   ,apl.phone_name   ,apl.phone_picurl1   ,apl.phone_picurl2   ,apl.phone_picurl3 from database1.pricelist pl inner join database2.allphonestable apl   on ap.phone_name = apl.phone_name 	0.0897065757232085
18822344	35228	external related table keys	select m.id as [master id],d.id as [detail id] from master_table m  inner join key_table mkt on (mkt.masterid = m.id) inner join master_table d on (mkt.relativeid = d.id) 	0.0140533641682724
18824075	31050	#1242 - subquery returns more than 1 row	select submissions.campid,         count(*) as subscounttotal,         sum(case when submissions.status = 10 then 1 else 0 end) as subscountngood  from submissions, campaings  where submissions.campid = campaings.id  and  campaings.status = 1 and   (   submissions.time <= campaings.enddate    or       (campaings.enddate = '0000-00-00' and submissions.time  >= campaings.startdate)  ) group by submissions.campid 	0.238025004009157
18826959	14795	select statement with rows as columns	select   (select username from [users] where rid = @user1rid) as level1user,   (select username from [users] where rid = @user2rid) as level2user,   (select username from [users] where rid = @user3rid) as level3user,   (select username from [users] where rid = @user4rid) as level4user 	0.0148550646201498
18829965	39750	counting rows in multiple tables cause large delay	select    (select count(*) from categories),    (select count(*) from serverfuncs),    (select count(*) from clientfuncs); 	0.0468893800013272
18837662	27914	skip/bypass data on a mysql_query	select * from foo where id%9=1 	0.0591594436916517
18849552	15491	create a summarized report using mysql query	select   cat,   sub_cat,   sum(amt) as total from   my_table group by   cat,   sub_cat 	0.54347941519566
18863557	2282	sql to return record counts in x intervals	select date(created_on - interval dayofweek(created_on) day), count(*) from t group by date(created_on - interval dayofweek(created_on) day); 	0.000116289777610103
18863713	2732	find missing number from not sequence number	select case when coalesce(a1,0)<>1 and coalesce(a2,0)<>1 and coalesce(a3,0)<>1              and coalesce(a4,0)<>1 and coalesce(a5,0)<>1 then 1 else '' end a         , case when coalesce(a1,0)<>2 and coalesce(a2,0)<>2 and coalesce(a3,0)<>2              and coalesce(a4,0)<>2 and coalesce(a5,0)<>2 then 2 else '' end b         , case when coalesce(a1,0)<>3 and coalesce(a2,0)<>3 and coalesce(a3,0)<>3              and coalesce(a4,0)<>3 and coalesce(a5,0)<>3 then 3 else '' end c         , case when coalesce(a1,0)<>4 and coalesce(a2,0)<>4 and coalesce(a3,0)<>4              and coalesce(a4,0)<>4 and coalesce(a5,0)<>4 then 4 else '' end d         , case when coalesce(a1,0)<>5 and coalesce(a2,0)<>5 and coalesce(a3,0)<>5              and coalesce(a4,0)<>5 and coalesce(a5,0)<>5 then 5 else '' end e     from numtest      where coalesce(a1,0)+coalesce(a2,0)+coalesce(a3,0)+coalesce(a4,0)+coalesce(a5,0)<>15 	0.000165494139020045
18867230	11798	sql query get max value at occured date	select hostname,         interface,         date_gmt,         intraf_mbps,         outtraf_mbps from traffic_report t where intraf_mbps + outtraf_mbps =       ( select             max(intraf_mbps + outtraf_mbps)          from traffic_report t2         where t2.hostname = t.hostname and               t2.interface = t.interface          group by hostname, interface       ) 	0.000515594647481176
18867645	12414	mysql group by with avg calculation	select originator, revenue, @r:=@r+1 as toprank, avg from (   select   originator, sum(total) as revenue, avg(total) as avg   from (     select   originator, date, sum(revenue) as total     from     my_table     group by originator, date     having   total <> 0   ) t   group by originator   order by revenue desc ) t, (select @r:=0) init 	0.717337190069931
18868234	5265	group countries together and count	select   country, emplevel, count(*) as count from     my_table where    country in ('uk', 'us', 'ca') group by country, emplevel union select   'global', emplevel, count(*) as count from     my_table where    country not in ('uk', 'us', 'ca') group by emplevel 	0.163464062568328
18873852	24003	select table name in query	select ''' + @zone +''' as zone ,e.networkid ,network.name as network ... 	0.0482037111479986
18889844	37260	grouping by two fields on same line	select a.questcode ,count(distinct a.customerid)as uniquecust, count(distinct  (case when a.questcode = b.questcode and  a.customerid = b.customerid then  b.customerid else 0 end) )-2, count(distinct  (case when a.questcode = b.questcode and  a.customerid = b.customerid then  b.customerid else 0 end) )-3, count(distinct  (case when a.questcode = b.questcode and  a.customerid = b.customerid then  b.customerid else 0 end) )-4 from fborder a inner join fborder b on a.customerid = b.customerid group by a.questcode 	0.000346232830861983
18921282	1151	store/select monetory values (credit/debit) mysql	select sum(if(type = 'dbt', -1 * amount, amount)) 	0.0724906220791736
18935515	110	mysql round 1583	select product_name, list_price, discount_percent,       round( (.01 * discount_percent) * list_price, 2 ) as discount_amount,       round( list_price - (.01 * discount_percent) * list_price, 2 ) as net_price from products; 	0.270354545998989
18936888	21486	sqlite, order by name if group doesnt exist	select * from mytable order by case coalesce(grouped, '')          when '' then name                  else grouped          end,          coalesce(grouped, '') <> '' 	0.316058267004024
18947048	1385	get multiple values from table	select c.firstname, group_concat(l.color) as colors from customers c inner join list_customer lc on lc.id_customer = c.id inner join list l on l.id_list = lc.id_list group by c.firstname 	0.000167361906367685
18947577	39189	mysql trying to reuse results of subquery in an efficient way	select      q,     count(x),     y,     i from      tablea a        inner join     tablec c        on cond and c.id = a.q        cross join      tableb b where     conds group by     q,      y,      i 	0.528677786015479
18954241	14989	sql server 2005 row to columns gps data mapping in scatter graph	select shiftindex, id, time, x00 as xgps, y00 as ygps from gps union select shiftindex, id, time, x01 as xgps, y00 as ygps from gps 	0.0490883349956613
18954954	25430	printing sql query result in a single line	select group_concat(`groupid` separator ',') from `tbl_groupassign` where `memberid` = 'check1' group by `memberid`; 	0.0588174000830783
18957970	13039	i have a table in database where i want to get last value of column	select max(date) from mytable where book_id = 41 	0
18976220	36444	get user friendly mssql server's product name	select left(@@version, charindex(' - ', @@version)) productname; 	0.00653958159767659
18977840	10725	mysql how to convert '2013-8-21' to date format	select str_to_date("2013-8-21","%y-%c-%d"); 	0.0197051807578743
18982048	12337	'conditional join' in mysql - (different joins under conditions)	select products.* from products inner join stores on stores.id = products.store_id and (stores.user_id = <supplied userid> or stores.is_active = 1) 	0.737330295917768
19000870	14360	hierararchy stucture in postgresql table	select parent,        coalesce(child1, parent) as child1,        coalesce(child2, child1, parent) as child2 from <tablename>; 	0.146436657003652
19032318	6544	calculation within mysql with a count	select numeric_values,count(numeric_values)as name from answertable group by numeric_values 	0.297475187768352
19035952	36973	how to run 2 queries at a time as single query	select name, (select avg(maths) from tbl),maths from tbl 	0.00482466552799081
19046812	15970	multiple count() for multiple conditions in one query (mysql)	select color, count(*) from t_table group by color 	0.0278252347237771
19058070	19969	mysql latest timestamp + other field with group by	select reportid, eventdatetime, eventtype  from testtracker_event t  where t.eventdatetime = (    select max(eventdatetime) from testtracker_event inner_t    where t.reportid = inner_t.reportid and t.testid = inner_t.testid    group by reportid, testid ) 	0.000112273117581002
19070124	317	sybase: how to get the current date in mm/dd/yyyy format?	select convert(varchar, date_column, 101) from the_table 	0
19078087	23117	how to get the total runs of each player and add it to an array?	select players.id, count(runs.pid) as runcount from players join runs on runs.pid = players.id group by players.id order by runcount desc limit 5 	0
19090042	38694	mysql query - show latest 3 records with order by ascending	select *     from (select *       from `comments` order by id desc limit 0 , 3) t order by id asc; 	5.70447522751489e-05
19091065	18832	mysql: multiple where query	select customer  from choices  where status = 1 and product in (1,3) group by customer having count(distinct product) = 2 	0.528010936113289
19099867	32415	sql add values from 2 tables	select distinct count(uniqueid), sum(wbid), uniqueid, firstname, lastname, email, phone, mobile, address, city from (    select l.uniqueid, r.wbid, l.uniqueid, l.firstname, ``l.lastname, l.email, l.phone, l.mobile, l.address, l.city    from edw..lookupuser l    inner join db..dimbd b on b.userid = l.userid    inner join db..factvp v on v.bidderid = b.bidderid    inner join db..factrd r on r.buyerid = b.bidderid and r.auctiondate > '2012-12-31'    union    select l.uniqueid, t.wbid, l.uniqueid, l.firstname, l.lastname, l.email, l.phone, l.mobile, l.address, l.city    from edw..lookupuser l    inner join db..dimb b on b.userid = l.userid    inner join db..factvp v on v.bidderid = b.bidderid    inner join db..factta t on t.bidderid = b.bidderid and t.auctiondate > '2012-12-31'    ) x group by uniqueid, email, phone, mobile, address, city, firstname, lastname order by email asc 	0.000365156897959408
19110418	15512	how to get customers age from mysql date	select timestampdiff(year, birthday, curdate()) as age from customer 	0
19118492	2505	bit field in where clause	select * from foo where firstname = 'xyz' and     (@active = 0 or active = <filter condition>) 	0.564960551868352
19121400	34541	mysql query limit per join	select * from (   select c.*, @row:=if(@parent=c.parent_id,@row+1,1) as _rn, @parent:=c.parent_id     from (select @parent:=null) as _init      straight_join comments c      inner join      (       select id       from comments       where depth = 0       order by id desc       limit 2     ) p on c.parent_id = p.id   ) as _ranked where _ranked._rn <= 5 	0.14458734643825
19135655	25682	negate sql query	select drivername  from driver  left outer join driverschedule on driver.driverid = driverschedule.driverid and scheduleid = 1 where driverschedule.driverid is null 	0.659436701489679
19136260	11490	h2 - dateadd for complete day	select * from statistics where timestamp > dateadd('day',-7, current_date)) 	0.143729820064278
19136444	5957	how to reduce query execution time for table with huge data	select 0 test_section, count(1) count, 'dd' test_section_value   from svc_order so, event e   where so.svc_order_id = e.svc_order_id     and so.entered_date >= to_date('01/01/2012', 'mm/dd/yyyy')     and e.event_type = 230 and e.event_level = 'o'     and e.current_sched_date between        to_date( '09/01/2010 00:00:00', 'mm/dd/yyyy hh24:mi:ss')       and to_date('09/29/2013 23:59:59', 'mm/dd/yyyy hh24:mi:ss')     and (((so.sots_ta = 'n') and (so.action_type = 0))         or  ((so.sots_ta is null) and (so.action_type = 0))         or  ((so.sots_ta = 'n') and (so.action_type is null)))   and so.company_code = 'll' 	0.760109341617803
19146249	9300	mysql - group results by weeks in a date range	select yearweek(`timestamp`, 1) yw,        count(id) as '# of new users in date range' from user  where inactive = 0 and timestamp between @startrangeselectdate and @endrangeselectdate group by yw 	0.000656435914605504
19159946	12395	combine count group by queries into single table	select accountid, subaccountid,     sum(case when successflag = 'false' then [count] else 0 end) as failed,     sum([count]) as total from mytable group by accountid, subaccountid 	0.00115342124397263
19163001	15425	merging two or more columns from different sql queries	select [t].*,        [d].[description] as [name],        [d2].[description] as [description] from   [trainerclass] as [t] join [descriptiontranslation] as [d] on [t].[code] = [d].[code]        join [descriptiontranslation] as [d2] on [t].[code] = [d2].[code] where  [d].[tablename] = 'trainerclass' and         [d].[fieldname] = 'name' and         [d].[language] = 'en-en' and        [d2].[fieldname] = 'description' 	0.000110150220261737
19169401	16537	mysql join two lists to check if a record exist	select   p.fullname,   p.email,   if(u.userid is null, 'false', 'true') registeredinsystem,   if(r.registrationid is null, 'false', 'true') registeredinevent from potentialusers p left join users on p.email = u.useremail left join registrations r on r.userid = u.id and r.eventid = 7 where p.fullname like '%jazerix%' 	0.00376344061168047
19175915	23480	mysql, filter duplicate sets	select t1.id as id1,    t2.id as id2,    t3.id as id3 from      mytable t1     mytable t2     mytable t3 where         id1 > id2 and id2 > id3 	0.0283669565817269
19177742	6263	sql: adding column from table b to table a	select distinct     a.id,     a.surveyid,     a.personid,     a.answer,     b.questionid,     b.question from tblanswers a inner join tblquestion b     on a.questionid=b.questionid 	0.000168912654412742
19184525	1212	mysql query within if condition	select * , if (t.sender_type='admin', a.owner, b.owner) as qowner  from transactions t  left outer join admins a on t.sender_id = a.id left outer join users b on t.sender_id = a.id having qowner in ('admin22','admin33','admin44','admin66') 	0.409046428995106
19190823	13933	sql if else statement during select?	select     [start_timestamp]   ,[end_timestamp]   ,[serial_number]   ,[model]   ,[testing_action_result]   ,[failed_step]   ,[disposition]   ,[testerid]   ,[location]   ,[customer]   ,case      when cast(substring([serial_number],3,2)as int)>90     then '19'+substring([serial_number],3,2)     else '20'+substring([serial_number],3,2) end as mfg_yyyy from [database_1].[dbo].[tbl_unit_test] 	0.584193133270639
19192348	42	getting average of column and value of another mysql	select e.datecreated      , max(if(e.idbank='tc',e.buy,null)) as tc      , avg(if(e.idbank='tc',null,e.buy)) as banks   from exchange e  group by e.datecreated 	0
19212341	12846	postgresql usage of aggregates and non-aggregate columns, grouping by	select         country.name,         city.name,         mp.maxpop from         lab6.country,         lab6.city,         (select                 country_code,                 max(population) as maxpop         from                 lab6.city         group by                 country_code         ) mp where         country.country_code=mp.country_code and         country.country_code=city.county_code and          mp.maxpop=city.population 	0.262599968107583
19215998	1685	sql views - modify returned result	select    column1,   column2 =      case       when date > 1999 then 'some value'       when date < 1999 then 'other value'       else 'back to the future'     end from .... 	0.200272122453974
19226206	27210	select column from table where number fall-in-range-of-text	select * from mark where x between pointermin and pointermax 	0.000448967912286739
19226713	3818	calling the same function multiple times in select	select      top10_fn_getmeasure006('04', '2012-01-01', '2012-12-31') as div04 ,   top10_fn_getmeasure006('05', '2012-01-01', '2012-12-31') as div05 	0.0230976359696783
19227011	20670	how to select and sum directly preceded related rows	select    *  , case    when d.sd_doc <> '' then    ifnull   (     ( select sum(d2.price)       from d_statistics_docs d2       where d2.sd_id >             ( select max(sd_id)               from d_statistics_docs d3               where sd_doc <> ''                 and d3.sd_id < d.sd_id              )         and d2.sd_id <= d.sd_id     )   , d.price     )   else d.price   end  totprev from d_statistics_docs d 	0.00203984548893724
19229105	22225	same type of value in a single row using case or decode	select m.pl_rpflag, sum(m.area) from  (   select (case when croptype_code < 13 then 'pedi' else 'paudha' end) as pl_rpflag,     nvl(sum(gh_area),0) as area   from w_cane_survey_2013   where unit_code = '03'      and gh_vill = '9991'      and gh_grow= '1' ) as m group by m.pl_rpflag 	0.00571115434730916
19232043	38646	concatenate ​​date values in postgres	select string_agg(to_char(datum, 'yyyy-mm-dd'), ','),        c1,         c2,        c3,         c4,         c5,         number from some_table group by c1, c2,c3, c4, c5, number 	0.00105299655469946
19237408	20463	grouping sub query in one row	select clientid,            sum(case when flag = 1 then 1 else 0 end) as gtcount,        sum(case when flag = 1 then amount else 0 end) as totalamountgreaterthan500,        sum(case when flag = 2 then 1 else 0 end) as lscount,        sum(case when flag = 2 then amount else 0 end) as amountlessthan500   from table1  group by clientid 	0.027849841129345
19240276	29413	how to get all table space name, allocated size, free size, capacity from single query?	select a.file_name,        substr(a.tablespace_name,1,14) tablespace_name,        trunc(decode(a.autoextensible,'yes',a.maxsize-a.bytes+b.free,'no',b.free)/1024/1024) free_mb,        trunc(a.bytes/1024/1024) allocated_mb,        trunc(a.maxsize/1024/1024) capacity,        a.autoextensible ae from (      select file_id, file_name,             tablespace_name,             autoextensible,             bytes,             decode(autoextensible,'yes',maxbytes,bytes) maxsize      from   dba_data_files      group by file_id, file_name,               tablespace_name,               autoextensible,               bytes,               decode(autoextensible,'yes',maxbytes,bytes)      ) a,      (select file_id,              tablespace_name,              sum(bytes) free       from   dba_free_space       group by file_id,                tablespace_name       ) b where a.file_id=b.file_id(+) and a.tablespace_name=b.tablespace_name(+) order by a.tablespace_name asc; 	0
19255491	9524	grouping strings with null values	select      order_id,      max(case when status = 'value' then status else null end) as status from table group by order_id 	0.0600068156471339
19269844	1121	how to create multiple rows from a single row	select     name   , seat   , ca1.aaisle   , ca1.baisle   , ca1.caisle from unpivotme cross apply (     values                  (fa1, fb1, fc1)               , (fa2, fb2, fc2)               , (fa3, fb3, fc3)             ) as ca1 (aaisle, baisle, caisle) ; 	0
19270838	40280	postgresql - how to convert one timestamp to another timestamp with its closer hour?	select date_trunc('hour', '2013-10-09 12:15:55.724+02'::timestamptz); 	0
19276762	17695	find the mode across several columns in mysql table for a specific row	select dataid from your_table where     if(jan, 1, 0) +     if(feb, 1, 0) +     if(mar, 1, 0) +     if(apr, 1, 0) < 3 	0
19279509	18334	mysql group by count	select from, to, count(*) as howmany,        sum(type = 'call_in') as call_in, sum(type = 'call_out') as call_out from table group by from, to 	0.220462901162801
19281191	7030	sqlite query to select new items with no history	select distinct mac from t where mac not in (     select mac from t where time < cast(strftime('%s', 'now', '-1 day') as integer) ); 	0.0121106821404822
19301398	1214	php mysql left join count column same id	select c.id, c.name, count(a.*) total from concorsi c     left join aste a on c.id = a.concorso_id group by c.id 	0.00972637162731164
19304464	31745	inserting from another table with conditions for a column	select ..., 'status' = case                     when somecolumn = 50 then 'status1'        when somecolumn = 51 then 'status2'        else 'defaultstatusvalue'   end from stg.submit s inner join dbo.dimproject dp on s.projectid = dp.projectid inner join stg.project sp on sp.projectid = dp.projectid), 	0.000302299572178467
19307165	5504	mysql searching with indexes	select `id`,`username`,`first_name`,`last_name`  from `users`  where (         `username` like 'kelon%'      or  `email` like 'kelon%'      or  `first_name` like 'kelon%'      or  `last_name` like 'kelon%'      or  `facebook` like 'kelon%'      or  `twitter` like 'kelon%'      or  `skype` like 'kelon%'     or  `username` like '%kelon%'      or  `email` like '%kelon%'      or  `first_name` like '%kelon%'      or  `last_name` like '%kelon%'      or  `facebook` like '%kelon%'      or  `twitter` like '%kelon%'      or  `skype` like '%kelon%' ) 	0.791720554478951
19308393	36	sql query: find highest revenue month/year for a customer	select customer,         year,         revenue,         month    from (        select customer,               year,               row_number() over(partition by customer order by revenue desc) as rank,               revenue,               month        from (               select customer,                       year(orderdatetime) as year,                       month(orderdatetime) as month,                       sum(revenue) as revenue               from   orders                group by                      customer,                      year(orderdatetime),                      month(orderdatetime)               ) bs     group by customer,              year,              month) bs2     where bs2.rank = 1 	8.4137571038458e-05
19317629	39940	cross joining to count values for a dates	select      calendardate, count(distinct bookings.id) from calendardate     left join          (           select              booking.id,              booking.depart,             vwreturndate.returndate           from booking             left join vwreturndate on booking.id = vwreturndate.id         ) bookings               on calendardate.calendardate between bookings.depart and bookings.returndate  where calendardate between '2013-10-01' and '2013-10-31' group by calendardate 	0.00523357548012466
19318437	40686	"distinct count" and "distinct count if exists" in single mysql select statement	select count(email) emails_sent, count(distinct email) unique_users, count(distinct if(not exists(select 1 from sent_emails where  date_sent < se.date_sent and se.email = email ),email,null)) new_emailed_users from sent_emails se where date_sent = '2013-01-10'; 	0.01097406441886
19318844	33170	total number of users at end of each week for last 6 months	select count(u.id) as total,        (select count(u.id)         from users u2         where week(u2.join_date) <=               week(u.join_date)         and u2.id = u.id) as total_count from users u where u.join_date>='$sixmonths' group by week(u.join_date) order by week(u.join_date) desc limit 26 	0
19321318	29441	how to get dfferent values using the same id in the mess table in oracle?	select id, major, major_id   from (select id,                major,                major_id,                count (distinct major) over (partition by id) as count_           from first_table)  where count_ > 1; 	0
19326631	25343	how to select distinct rows where 2 columns should match on multiple rows?	select distinct up.user_id  from user_params as up left join user_params as upp on up.id = upp.id group by up.user_id having sum(param_id = 44 and param_value = 'google') >= 1 and sum(param_id = 45 and param_value = 'adtest') >= 1 	0
19334825	16106	how can i use a csv list for an sql select query?	select * from some_table where some_table.id in (     5,    10,    31,    72 ) 	0.184985839391761
19340154	23048	t-sql projection/forecast/calculation questions with cte based on datetime and uniqueness	select      company,     src_amount,     src_projectedfromhrate,     dateadd(m, n.number, src_fulldate) as projecteddate,     src_amount * power(1+project_againstrate, number) as projectedvalue from test_tbl t,     (select * from master..spt_values where type='p' and number between 1 and 48) n 	0.0365680118887021
19350199	14206	order by date a select query on union all	select id, date, text from (select id, date, text, 1 as priority       from timeline       union all       select *, 2 as priority       from reps) u order by priority, date desc 	0.00836719787733815
19351638	8155	mysql add 0 when < *.10	select case     when instr(id, '.') = 0 then id     else case          when cast(substring_index(id, '.', -1) as unsigned) < 10 then                concat(substring_index(id, '.', 1), '.0', cast(substring_index(id, '.', -1) as unsigned))          else id     end end as result from table_name update table_name set id = case     when instr(id, '.') = 0 then id     else case          when cast(substring_index(id, '.', -1) as unsigned) < 10 then                concat(substring_index(id, '.', 1), '.0', cast(substring_index(id, '.', -1) as unsigned))          else id     end end 	0.0280937246730939
19354582	15764	how to use max() in join query	select     rec.rec_id_i,     rec.rec_no_v,     cus.cus_name_v,     rec.rec_paidamount_m,     case         when rec.rec_paymode_c = 'c' then 'cash'         else 'cheque'     end as rec_paymode_c,     rec.rec_bankname_v,     rec.rec_bankaddress,     rec.rec_chequeno_v,     convert(varchar, rec.rec_chequedate_d, 103) as rec_chequedate_d,     rec.rec_date_d,     recid.maxrecid as recid from tbl_receipts rec join tbl_customermaster cus on rec.rec_customerid_i = cus.cus_id_i join (select max(rec_id_i) as maxrecid, rec_customerid_i from rec group by rec_customerid_i) as recid on recid.rec_customerid_i = rec.rec_customerid_i where   rec_active_c='y'   and rec_salesmasterid_i='0' order by rec_id_i 	0.637233441143078
19355643	5898	database design for images	select coalesce( b.image, p.imagedata ) from buddy b, predefined_images p  where b.imageid = p.id 	0.298128940340326
19371004	36268	mysql joining 2 tables getting 2 diferent values from the same table	select f.name, t.name, message from messages left join users as f on messages.fromid = f.uid left join users as t on messages.toid = t.uid 	0
19385580	30851	how do i select rows from one table as csv and insert into another table based on a key?	select testa.id, testa.dcac, group_concat(testb.x) from testb inner join testa on testb.a_id = testa.id group by testb.a_id 	0
19402556	27698	how to creat a week,mount, year summary of a database	select company_name, yearweek(date), sum(weight) from table group by company_name, yearweek(date) 	0.000775261511071569
19423807	16269	select the sum of multiple values to which user is subscibed	select a.id, a.lastname, a.name, a.balance, b.maxdebt from (select customers.id as id, upper(lastname) as lastname, name, sum(cash.value) as balance       from customers       join cash on customers.id = cash.customerid       where deleted = 0 and cutoffstop < 50       group by customers.id, lastname, name) a inner join (select sum(tariffs.value) as maxdebt, customers.id as id             from tariffs             inner join assignments on tariffs.id = assignments.tariffid             inner join customers on assignments.customerid = customers.id             group by id ) b on a.id = b.id and a.balance < b.maxdebt 	0.000222304381418037
19432210	6364	mysql - how can i do a join and order by the sum of votes?	select entry_id from contest_entries left outer join contest_votes on entry_id = contest_entry_id group by entry_id order by sum(vote) desc 	0.0247523419459145
19437249	28111	sql select two columns from one table translated by a column from another table	select p.first, p.last, c.first, c.last from parent_child_table pc  inner join people_table p on p.id = pc.parent inner join people_table c on c.id = pc.child 	0
19450634	2937	sql statement for selecting information from 'next' row, last record drops off	select t1.state_id, t1.created as starttime, t2.created as endtime  from state t1 left join state t2    on t1.asset_id = t2.asset_id    and t1.created < t2.created where t1.created like "2013-10-13%" and t1.asset_id=97    and not exists     (select *      from state      where state.created > t1.created       and state.created < t2.created) order by starttime 	0
19450884	32499	marking results in sql	select      case          when age>10 then 'age'          when weight>100 then 'weight'          else 'status'      end case      ,*  from people where age>10 or weight>100 or status in ('active','paying','dead') 	0.327098814482505
19465189	38545	mysql combine 2 rows into one	select i.id,         u.iosurl as imageurlios,        u.iosretinaurl as imageurliosretina,         ur.iosurl as bannerimageurlios,        ur.iosretinaurl as bannerimageurliosretina  from item i  left join imageurl u on u.id = i.imageurlid left join imageurl ur on ur.id = i.bannerimageurlid 	7.75389679100811e-05
19493276	19397	mysql query to count the number of entries grouped by name	select company_id, count(company_id) from tablename group by company_id 	0
19494600	26526	mysql - show all results, including 0 results	select * from article as a inner join comment as c on a.article_id = c.article_id; 	0.00200945734552721
19497253	8693	how do i use a procedure to run a select that exports to an excel spreadsheet?	select dbms_xmlquery.getxml('select * from ' || table_name) from user_tables; 	0.503938560416689
19507718	12170	sql group by with an order by latest on another column	select mn.meter_name, m.meter_number, m.meter_location, r.rates_meter_rate,      r.rates_meter_ppd, m.meter_id, mt.metertracking_periodend,     mt.metertracking_read, mt.metertracking_readend  from db_meters m, db_meters_name mn, db_rates_meter r, db_meters_tracking mt  where m.icp_id = '$icp' and m.meter_name_id = mn.meter_name_id  and r.meter_id = m.meter_id and r.contract_id = '$contract_id'  and mt.meter_id = m.meter_id and metertracking_periodend = (     select max(metertracking_periodend)      from db_meters_tracking     where meter_id = mt.meter_id     group by meter_id ) order by metertracking_periodend 	0.000619436491598846
19514187	8187	mysql - merge messages and replies by user	select email, content, time_sent   from messages  union all select m.email, r.content, r.time_sent   from replies r join messages m     on r.message_id = m.message_id  order by email, time_sent 	0.00828793138117388
19514532	33247	mysql get last date records from multiple	select id, type, max(datetime) from your_table group by id, type 	0
19542296	26328	reverse order of sql query output	select * from (     select * from lastresult order by date desc limit 10 ) as order by date asc; 	0.456295684652349
19548171	21592	getting a count of distinct entries and what that entry is	select [name], count(foo1) as cnt from tablename group by [name] order by [name] asc 	0
19548398	2301	return next available pk in a collection of tables	select col.table_name, col.column_name, ident_current(col.table_name) from      information_schema.table_constraints tab,      information_schema.constraint_column_usage col  where      col.constraint_name = tab.constraint_name     and col.table_name = tab.table_name     and constraint_type = 'primary key ' 	0.000125165117466313
19549342	562	how to extract data from table using in sql server management studio	select @strs = name from companies where ... 	0.330551925606575
19556564	19456	mysql query join table selecting highest date value	select cll.cl_id, cc.cc_id, cc_rego, cc_model, cll.cl_datein, cll.cl_dateout from courtesycar cc, courtesyloan cll where cl_datein = (    select  max( cl.cl_datein )   from courtesyloan cl   where cl.cc_id = cc.cc_id ) and cc.cc_id = cll.cc_id 	7.72916731019043e-05
19562290	30671	how can i get same ip count group by name?	select name,        count(*) as count,        count(*) - (count(*) - count(distinct ip)) as same_ip_count from p  group by name 	0.000532391579382892
19564965	35604	select row values that are in repeated rows that have a colum with at least 3 different values	select ma,        count(distinct mi) as num from atablelikethis group by ma having count(distinct mi) >= 3 	0
19605140	20084	sql check if timestamp is greater than 24 hours from now (mysql)	select * from news where date >= now() + interval 1 day; 	0
19605497	40110	add a record to last of the table	select top 1 catid, title, parentid, url, crawlercheck from tblcrowler where catid=(select min(catid) from tblcrowler where crawlercheck=1) update tblcrowler set crawlercheck=2 , hasdata=2 where catid=(select min(catid) from tblcrowler where crawlercheck=1) 	0
19606656	27931	check user's rights on a ssrs	select      dbo.users.username,     dbo.roles.rolename,     substring(dbo.catalog.path,2,len(dbo.catalog.path)) foldername from      dbo.policyuserrole  left join dbo.users       on dbo.users.userid=dbo.policyuserrole.userid left join dbo.roles       on dbo.roles.roleid=dbo.policyuserrole.roleid inner join dbo.catalog       on dbo.catalog.policyid=dbo.policyuserrole.policyid where      type=1 	0.00584234899279754
19608325	35673	get number of employees who worked in more than one department with sql query	select count(*) from ( select id_employee, count(*) as cnt from department_employee group by id_employee ) as t where cnt > 1 	0
19623436	10522	extracting dates from mysql in php	select     `name`,     `start-date`,     `end-date` from     `table of events` where     `start-date` between '2013-10-01 00:00:00' and '2013-10-31 23:59:59' or     `end-date` between '2013-10-01 00:00:00' and '2013-10-31 23:59:59'; 	0.00138685085845692
19626372	29018	how to do calculation like sum and others with sql statement in sqlite	select sum(amount) from transactionline where sid = 1 	0.752038505257413
19628922	30034	how to write query to get the output as shown below in my sql	select t1.bill_date as `date`, t1.total as credit, t2.amount as debit  from bills t1 left join payments t2 on t1.bill_date= t2.paid_on union select t2.paid_on as `date`, t1.total as credit, t2.amount as debit from bills t1 right join payments t2 on t1.bill_date <> t2.paid_on union select t1.bill_date as `date`, t1.total as credit, t2.amount as debit  from bills t1 left join payments t2 on t1.bill_date <> t2.paid_on 	0.396051163355463
19637678	1016	average number of rows created per day?	select count(*) / count(distinct date(created_at)) from your_table 	0
19645010	9759	mysql - finding out where the max value comes from	select  id,  greatest(l1_rms, l2_rms, l3_rms) value,         case greatest(l1_rms, l2_rms, l3_rms)          when l1_rms then 'l1_rms'          when l2_rms then 'l2_rms'          when l3_rms then 'l3_rms'          end columnname  from table 	0.000642983631221868
19647941	37146	select rows where a value matches another value in another table	select a.id, a.subject, a.date, c.companyname from activity a  inner join company c on a.companyid = c.companyid inner join companygroup cg on c.companyid = cg.companyid where cg.groupid = 1 	0
19648101	29004	get data from relational tables	select distinct p.id as personid, n.name as note, c.name as call from person p inner join personcalls pc on p.id = pc.personid inner join personnotes pn on p.id = pn.personid inner join calls c on pc.callid = c.id inner join notes n on pn.noteid = n.id 	0.00136712511107674
19649494	26608	how to get the average for one column of data in sql server	select  * from [enterprise].[dbo].[employee] where ed_lvl > (select  avg(ed_lvl) from [enterprise].[dbo].[employee]) 	0
19650201	8306	sql query to get data for spacetree (jit)	select bt.parid,bt.custid,cu.firstname  from binarytree bt inner join customers cu on bt.custid=cu.custid order by bt.parid,bt.custid 	0.0361141091356411
19656991	5030	how to write count query in jooq	selectquery<record> selectquerycount = transaction.selectquery();  selectquerycount.addfrom(table);  result<record> resultobject = selectqueryrecord.fetchcount(); 	0.545219915068752
19665431	34019	get the duplicate records based in 2 columns	select o.emp_id  from orders o  group by o.emp_id   having count(distinct o.item_id) <> count(*) 	0
19669494	1046	select from table depend on value from two column	select * from `prim_3` where    (unit = '1' and lesson = '3') or   (unit = '3' and lesson = '4') 	0
19679119	10225	getdate() method for db2	select current date - 1 day from sysibm.sysdummy1 	0.75458459931391
19679455	33389	aggregate value under different conditions	select     sum(case when assignment.job_id is not null then 1 else 0 end) as assignedjobs,     sum(case when assignment.job_id is null then 1 else 0 end) as unassignedjobs,     count(*) as totaljobs from job left join assignment on assignment.job_id = job.id 	0.0178779053566586
19680378	26277	sql oracle sum after each periode	select    case when vessel_name is null then 'total' else to_char(period) end as period,   case when vessel_name is null then 'period' else vessel_name end as vessel_name   , sum(total_amount) from the_table group by rollup(period, vessel_name) having period is not null; 	0.00454502515259585
19687951	32550	pl/sql pseudo sequencing	select t.id, s.seq   from (select distinct id from mytable) t       ,(select rownum as seq          from   dual          connect by level <= 6) s minus select id, seq   from mytable order by 1, 2 	0.727188995382175
19688352	18027	conditional mysql order by	select name, points, pot, multiplier from items order by   multiplier desc,   pot <= 80,   points desc 	0.749087491993078
19693859	28031	t-sql add delimiter between data when using openrowset and xml	select     c.value('(name)[1]', 'varchar(max)') as [name],     nullif(       replace(         c.query('           for $i in stuff/note/text()           return concat($i, ",")          '         ).value('.', 'nvarchar(max)') + ','       ,',,','')     , ',') from @data.nodes ('/root/item') as t(c) 	0.293750294372413
19706741	34595	get records of a table doesnt exists in another table + sql server	select tablea.* from tablea left join tableb   on tablea.aid  = tableb.aid  and tablea.aiid <= tableb.aiid where tableb.bid is null; 	4.65366465597991e-05
19707750	10912	storing and comparing time for multiple timezones	select convert_tz(concat(curdate(),' ',time),zone,'gmt') from config; + | convert_tz(concat(curdate(),' ',time),zone,'gmt') | + | 2013-10-31 10:01:50                               | | 2013-10-31 11:07:36                               | | 2013-10-31 10:01:50                               | | 2013-10-31 06:07:20                               | + 	0.0444109082617336
19714830	2531	get intersection of sets in mysql db	select t2.person_id, count(*) int_size, group_concat(t2.preference_id) shared_preferences from table t1 join table t2 on t1.preference_id = t2.preference_id where t1.person_id = 1 and t2.person_id != 1 group by t2.person_id order by int_size desc limit 10 	0.00533065926455503
19717967	5906	need to print a statements based on an if and else constriction	select    order_line.o_id,   case when      sum(inventory.inv_price) > 100 and sum(inventory.inv_price) < 200    then     sum(inventory.inv_price)*0.9   when sum(inventory.inv_price) > 200 then     sum(inventory.inv_price)*0.8   else     sum(inventory.inv_price)   end sum from inventory inner join order_line on inventory.inv_id = order_line.inv_id inner join item on item.item_id = inventory.item_id group by order_line.o_id order by order_line.o_id 	0.0346181683294081
19719805	5542	sql count users with min date of login?	select count(*) from (select user       from table       group by user       having min(login_date) = '10/3'      ) t 	0.00321733789693489
19727815	21095	mysql combine strings from many rows like sum for int	select sum(id), group_concat(text separator '.') from t 	0.00222255356950783
19735488	20309	oracle sql: creating unique teamid from existing table	select upper(substr(deptname,1,3)) || upper(substr(color,1,2))  || rownum from dept; 	0.00963441798702184
19735934	15754	oracle: select multiple values from a column while satisfying condition for some values	select col from table where     col > 3 union select max(col) from table where     col <= 3 	0.000453100301648129
19752906	3840	creating queries in sql	select a.name, m.mentor from accountant as a left outer join accountant as m on a.mentor = m.staff_id where m.mentor is null order by m.surname; 	0.706363329569722
19754513	12008	intersecting tables with multiple return values	select empid from hasskill, job where jobid = 1 and skillid = needskill group by empid having count(0) = (select count(0) from job where jobid = 1) 	0.00537768703953691
19758841	24680	query to get latest 10 rows by using id's from other table	select * from posts where poster_id in      (select following_id from followers where user_id = ?) order by posted_at desc limit 10 	0
19759049	19754	sql: querying within multiple records that represent the same individuals	select distinct studentid from alumni where studentid not in (     select studentid from alumni where state_fee = 'state' ) 	0.000311332993255958
19763806	26469	mysql ignores null value when using max	select id, case when max(date is null) = 0 then max(date) end as date from test group by id; 	0.448085014515285
19770786	36083	sql query to turn audit trail in / out times to list of locations	select * from (select "widget id" id,  "new location" loc, "date" start_date,  lead("date", 1, sysdate) over (partition by "widget id" order by "widget id") end_date from widgets) t where t.loc = 101 and start_date < <<your_ending_date>> and end_date > <<your_starting_date>> 	0.00176674585328452
19780251	2274	joining table to itself and selecting values that don't match	select t1.data as t1_data from test t1 where t1.id between 1 and 3 and not exists(   select *   from test t2    where t2.data = t1.data   and  t2.id > 6   ); 	0
19788717	37851	mysql project design - conditionally select from one table based on rows from another select query	select listing, b.bed, bath, type, address, postcode, state, price     from         buy_items b     join (     select bed, bath, type, suburb, postcode, avg(price) as avg_price     from rent_suburbs     group by bed, bath, type, suburb, postcode ) a     on a.bed=b.bed and a.bath=b.bath and a.suburb=b.suburb and a.postcode=b.postcode     where (b.price*.0014) < a.avg_price; 	0
19806241	40818	group conversation by users mysql select for messages	select message from messages  where 1 in (from_user_id,to_user_id) and 3 in (from_user_id,to_user_id) 	0.0129850988917744
19808547	6558	sql subtract time from a datetime	select dateadd(hour, -datepart(hour, timetolive), getdate()); 	0.00127815623415425
19809940	6632	getting team name, count of victories, count of played	select op.id, op.name, sum(if(o.opponent_id = m.winner_id, 1, 0)) victories, sum(if(m.statut = 3,1,0)) played from opponents as op left join odds o on op.id = o.opponent_id left join matches m on o.match_id = m.id group by op.id order by victories desc; 	0.00103795802689196
19815827	37108	numbering of unique combinations of columns	select      id, dense_rank() over(order by a,b,c,d) as gid from tmp 	0
19823942	26894	limit before distinct	select a.no, count(*) total    from (         select no from test order by no desc limit 5        ) a   group by a.no    order by total desc; 	0.10728134043952
19831812	6401	joining 2 tables in sql using a common third	select   c.cid,    c.cname,    r.regionid,    r.regionname from   regions r    inner join branch b on b.regionid = r.regionid   inner join countries c on c.cid = b.cid; 	0.000963447091432483
19834362	22158	how to get highest integer value from mysql table php	select max(number) from number 	0
19836600	21043	summing value of column a for each distinct value of column b	select max(saleid),enginetype,motion,sum(quantity) from table group by enginetype,motion 	0
19851322	30842	query duplicate records	select it.[name],it.[tel] as it , sales.[tel] as sales from (select [name], [tel] from table1 where [department] = 'it') as it inner join (select [name], [tel] from table1 where [department] = 'sales') as sales on it.[name] = sales.[name] 	0.00970299346827504
19857424	30982	mysql query null value is not including in where condition	select * from venue_event  where owner_account_id=3 and venue_id=1 and (status != 'paid' or status is null) 	0.455831078726371
19862306	4659	returning only records that have matching fields in other records	select * from  customers c join      (select address1, postcode from customer group by address1, postcode having count(1) > 1) c2          on c.address1 = c2.address1 and c.postcode = c2.postcode 	0
19868046	29047	sql server 2008, convert decimal value to percentaje withouth rounding?	select '%'+left(cast((0.96774*100) as varchar),5) 	0.169795789353803
19872981	27308	sql how to expand table to more filed base on one filed's value	select min(tt.id) as id,         tt.name,        tt.age,         isnull(cast(sum(points20131) as varchar(10)),'na') as 'points20131',        isnull(cast(sum(points20132) as varchar(10)),'na') as 'points20132',        isnull(cast(sum(points20133) as varchar(10)),'na') as 'points20133' from (    select id,            name,           age,            case when yearquarter = '20131' then points else null end as 'points20131',            case when yearquarter = '20132' then points else null end as 'points20132',            case when yearquarter = '20133' then points else null end as 'points20133'     from test ) tt group by tt.name, tt.age order by min(tt.id) 	9.14721817257578e-05
19903358	34616	how to select sub string from a column of type varchar2?	select    regexp_substr( mycolumn, 'queen.+queen' ) as case1 , regexp_substr( mycolumn, 'queen.+?queen' ) as case2 from (   select 'king queen jack king queen' as mycolumn   from dual   union all   select 'king jack queen ace jack queen king' as mycolumn   from dual   union all   select 'queen ace queen king queen jack' as mycolumn   from dual ); 	0.000820896165001593
19906524	20889	display data from table1 where its id (table1 id)is not contained in table2	select * from table1 where not exists(select table1id from table2 where table1id=table1.id) 	0
19907391	39574	how to create where condition with tuples	select user_id from "user" u join org_cat on u.company_id = org_cat.company_id  and u.subcompany_id = org_cat.subcompany_id  where org_cat.cat_id = 2 	0.173392820798267
19907458	5157	top 10 players ranked by score + curent player score	select rank, player_id, plscore  from table_name where rank < 11  or player_id = current_player_id  order by rank; 	6.2322749704116e-05
19914804	32960	multiple join mysql	select t1.name, t2.name, t3.user_prediction from predictions as t3 join teams as t1 on (t3.home_team_id = t1.team_id) join teams as t2 on (t3.away_team_id = t2.team_id); 	0.438967010481129
19921738	21112	group by customer name	select row_number() over (order by visit_date desc,p_name asc) as rownumber, *  from (select distinct p_master.p_name, (select max(visit_date) from p_visit v where v.pid = p_master.pid) as visit_date from p_master left join p_visit on p_master.pid=p_visit.pid where p_master.p_name like 'j%') tbl 	0.0085218906187206
19934401	29882	selecting remove duplicate entries using 2 fields from oracle	select distinct unique_customer_id, message_id, max(date) from tablename group by unique_customer_id, message_id 	0
19936923	24038	tsql query count with multiple columns	select tag, count(*) from table group by tag 	0.0791026193166744
19938155	4607	mysql select based on friendship status of current user with searched user	select distinct u.name_surname, u.avatar, u.location from users as u left join connections as c   on c.user_id = u.id     and c.deleted <> 1 left join words_en as w    on w.id = c.word_id left join friends as f1   on f1.asker_user_id = :person1     and f1.status=1     and f1.asked_user_id = u.uid where (w.word = :kwd   or u.location = :kwd   or u.name_surname = :kwd) and (u.privacy=3 or (u.privacy=2 and f1.id is not null)) 	0
19942196	2166	get ssas cube last process time	select last_data_update from $system.mdschema_cubes 	0.00185386629437206
19942960	28434	how to label inner join column result	select dbo.findintersectingzone(location) as 'zone', count(*) as no_of_stations from londonstations inner join [planning_districts_2008_updated]   on [planning_districts_2008_updated].geom.stintersects(stations.location) = 1 group by dbo.findintersectingzone(location) 	0.180591687881304
19982744	9031	t-sql puzzler - given a cell in an n-dimensional space, return the cells that are inline with the given cell along each axis	select x.axiscode, a2.cellid from cellaxes a1 inner join cellaxes a2 on a2.axiscode = a1.axiscode inner join cellaxes x on x.cellid = a1.cellid where (a1.axiscode = x.axiscode or a1.positiononaxis = a2.positiononaxis) and a1.cellid = @cellid  group by x.axiscode, a2.cellid having count(*) = (select count(distinct axiscode) from cellaxes where cellid = @cellid) 	0
19988362	2688	how to select rand() between 1-n	select id, name from   (select id, name from table order by id desc limit 3) s order by rand() limit 1 	0.0536692496791315
19991370	23532	sql numeric to date (with an exception)	select wmacct# as 'account #',   case      when opendt = 0 then '2013-10-31'         else convert(date, convert(varchar(8), opendt), 104)     end as 'open date',   case      when date = 0 then null         else convert(date, convert(varchar(8), cldt), 104)     end as 'close date' from server.server 	0.607122656113106
20001049	39393	count number of rows within each month of a datetime, group by year month	select  convert(varchar(4),year(lastmodifeddate)) + ' ' +          convert(varchar(3),datename(month,lastmodifeddate)) as dates,         count(*) as number from aims.modification where companyid = @companyid      and lastmodifeddate >= dateadd(month,@numberofmonths * -1,getdate()) group by convert(varchar(4),year(lastmodifeddate)) + ' ' +           convert(varchar(3),datename(month,lastmodifeddate)),          convert(varchar(6),lastmodifeddate,112) order by convert(varchar(6),lastmodifeddate,112) 	0
20004845	36364	sql query writing help - multiple lookups in one record	select t.turnid,      t.throw1,      t.throw2,      t.throw3,     (select value from scorevalues where score = t.throw1) as throw1value,     (select value from scorevalues where score = t.throw2) as throw2value,     (select value from scorevalues where score = t.throw3) as throw3value, from turns t 	0.725622939670555
20009740	6463	ms sql server: create a sequence based on a column's value	select a.city, b.number sequence from cities a cross join (select *             from master.dbo.spt_values             where type = 'p'             and number > 0) b where b.number <= a.numberofschools 	0.000203557436227437
20017881	19534	select all items, order by number of times item used	select v.id, count(*) from venues v, events e where v.id = e.id group by v.id order by count(*) desc; 	0
20019172	9506	multiple joins - mysql	select s.class     ,count(s.id_student) as nr_students     ,g.avg_grade as avg_grades     ,sum(a.cnt_absences) as absences from students s  inner join (     select s.class, avg(g.grade) as avg_grade      from grades g     inner join students s on g.id_student = s.id_student     group by s.class   ) g on s.class = g.class left join (     select id_student, count(id) as cnt_absences      from absences       group by id_student   ) a on s.id_student = a.id_student group by s.class, g.avg_grade 	0.608318987636099
20020163	39078	mysql increment or not based on a previous value	select id, percent, rank from (     select id, percent      , @currank :=            case             when @prevparent = parent then                case                    when @prevcent = percent then @currank                     else @currank + 1                end            else 1         end rank     , @prevparent := parent     , @prevcent := percent     from      (         select child.id, child.percent, child.parent         from likesd parent         inner join likesd child            on child.parent = parent.id         where parent.type = 3         order by parent.id         , child.percent desc     ) x     cross join (select @currank := 0, @prevparent := null, @prevcent := null) r ) y 	0.000161230784225302
20020832	39459	select sum of an array column in postgressql	select id, (select sum(s) from unnest(monthly_usage) s) as total_usage from users; 	0.012078774388308
20033208	28277	display multiple results with inner join	select c.name_company, group_concat(s.name_service separator ', ') as services from auxiliary a join      companies c      on a.id_company = c.id_company join      services s      on a.id_service =  s.id_service group by c.id_company, c.name_company; 	0.156731205758307
20049809	16449	interpreting sumif in excel sql	select column_material, sum(column_stockquantity)   from youtablename    group by column_material 	0.625490450099377
20050511	8676	joining a table to itself based on a "connection" table	select a.unique_flat_title as category_flat_title      , c.id as post_id , c.unique_flat_title as post_title from items a  join item_connection b on  b.category_id = a.id join items c on c.id=b.post_id 	0.000153808301050248
20052942	32329	uniquely left join many to many table	select     avalues.a_id,     avalues.item_id,     bvalues.b_id from (select     a_id,     item_id,     row_number() over(partition by item_id order by a_id) arowid from         table_a) avalues inner join (select     b_id,     item_id,     row_number() over(partition by item_id order by b_id) browid from     table_b) bvalues on avalues.item_id = bvalues.item_id and avalues.arowid = bvalues.browid 	0.332915802694431
20053798	24254	finding relationship records for which there is no reverse relationship	select r1.* from relationships r1   left join relationships r2     on r2.origin_id = r1.target_id       and r2.target_id = r1.origin_id where r2.origin_id is null 	0.00109979322650811
20062065	9508	select 2nd to last date with group by	select mn.meter_name, m.meter_number, m.meter_location, r.rates_meter_rate,        r.rates_meter_ppd, m.meter_id, mt.metertracking_readend,                                mt.metertracking_conversion, mt.metertracking_periodend  from db_meters m inner join db_meters_name mn on m.meter_name_id = mn.meter_name_id      inner join db_rates_meter r on r.meter_id = m.meter_id       inner join db_meters_tracking mt on mt.meter_id = m.meter_id where m.icp_id = '227' and r.contract_id = '70'  and 2 = (select count(distinct a.metertracking_periodend)      from db_meters_tracking a       where a.meter_id = r.meter_id and mt.metertracking_periodend <= a.metertracking_periodend) order by m.meter_id, metertracking_periodend 	0.000127057184661216
20081722	17172	mysql get last date from table that has not yet passed	select * from table_a  where curdate() <= date_created 	0
20082401	4868	creating a mysql outfile with a timestamp	select *, current_timestamp as extract_dt from customer into outfile 	0.409186396795761
20083790	15681	using sys.fn_isbitsetinbitmask in sql azure	select dbo.what(); 	0.594334737622599
20103568	7975	sql counting distinct records and grouping the count by the record name	select   [issuing natin], count(*) from     [201310] where    [visa type] in ('f1', 'j1') group by [issuing natin] 	0
20106424	7154	how to join, including row with null data	select a.custid, a.companyname,         b.orderid, b.orderdate from sales.customers as a   left join sales.orders as b    on a.custid=b.custid; 	0.0188246133499181
20108482	24589	how do i merge rows from a select statement based on conditions	select      number,     isnull( type,         (select top 1 type from table t1 where t1.number = t.number) ) as type,     name from      table t 	0
20119282	25623	how to display two digits after decimal in sql server	select cast(your_float_column as decimal(10,2)) from your_table 	0.000354409253957641
20123735	31646	how can i find the row error for a table without an auto-increment?	select *, char_length(foo) from table_name order by char_length(foo) desc limit 25 	0.0175992911459798
20123945	24657	sql server : split csv	select identifier, ltrim(t2.my_splits) as my_values  from   (    select *,    cast('<x>'+replace(t.values,',','</x><x>')+'</x>' as xml) as my_xml     from yourtable t   ) t1   cross apply   (    select my_data.d.value('.','varchar(50)') as my_splits   from t1.my_xml.nodes('x') as my_data(d)   ) t2 	0.0878030793193985
20125094	19321	select element where condition is met on all joined elements	select f.folderid,     count(fls.fileid) as filescount,     sum(a.surname = 'x' and a.firstname = 'y') as authorfilescount from `folders` f       inner join `file_relation` rel on rel.folderid = f.folderid       inner join `files` fls on fls.fileid = rel.fileid       inner join `authors` a on a.authorid = fls.authorid  group by f.folderid having filescount = authorfilescount; 	8.9126886380237e-05
20127672	35452	sql server : query for instances of a bit that is 0 for all codes in a table	select * from people p, people_codes c where p.person_id = c.person_id and p.person_id not in (select person_id from person_codes where primary = 1) 	0.000991569821170326
20130592	26353	return all rows/columns where multiple columns are non distinct	select t1.* from     [dailytaskhours] t1 inner join (   select       activitydate, taskid   from       [dailytaskhours]   group by       activitydate, taskid   having        count(*) > 1 ) t2 on (   t1.activitydate = t2.activitydate and   t1.taskid = t2.taskid ) 	9.09440191896212e-05
20136172	6795	build select result based on multiple column values	select case africanamerican when 1 then 'african american/' else '' end         + case white when 1 then 'white/' else '' end         + case hispanic when 1 then 'hispanic/' else '' end     from persontable 	0.000315091496510824
20143421	15555	multiple expressions in mysql if condition	select `t1`.`k1`,        case when sum(`t1`.`k1`) = sum(`t2`.`k1`) then 'equal'             when sum(`t1`.`k1`) > sum(`t2`.`k1`) then 'greater'             else 'less'        end as state from `t1` inner join `t2` on `t1`.`code` = `t2`.`code` group by `t1`.`k1` 	0.636844764439158
20148785	17896	products with only one available colour in stock - sql query	select * from product where substr(product,1,6) in ( select substr(product,1,6) from product  where not (product like '%.000.%') group by 1 having count(1) > 1 and sum(productqty)=1 ) 	0.000606736634630235
20149594	30595	merging an unknown number of result sets in sql server	select col1, col2, col3 from tablea where ...  union select  col1, col2, col3 from tablea where ...  order by col1, col2 	0.00839109030447757
20150011	22840	how to get counts of occurrences from two tables	select i.id,i.name,count(*) from items i inner join things t on t.item_id = i.id group by i.id, i.name order by i.id 	0
20151183	9752	need sum of distinct values in one mysql column grouped by the distinct value	select country, count(*) as count  from contact group by country order by count desc 	0
20158300	22559	sql where insert	select recording_artist.artist_name,musical_genre.musical_genre,     count(musical_genre.musical_genre) as songs from recording_artist     full outer join album         on recording_artist.recording_artist_id = album.recording_artist_id     right outer join song         on album.album_id = song.album_id     inner join musical_genre         on album.musical_genre_id = musical_genre.musical_genre_id where musical_genre.musical_genre = 'rock' group by recording_artist.artist_name,musical_genre.musical_genre; 	0.469156174764564
20161496	5349	mysql join two additional columns into query	select deb.id, t1.name as visitor , t2.name as host, s.name from debates as deb inner join teams t1 on t1.id = deb.visitid inner join teams t2 on t2.id = deb.hostid inner join states s on t2.stateid = s.id group by id 	0.013782808552944
20161764	37286	mysql many-to-many intersection using a single query	select     distinct(m1.id_person) from     meetings m1, meetings m2 where     m1.id_employee=:employee2 and     m2.id_employee=:employee1 and     m1.id_person = m2.id_person 	0.252531469776493
20163805	6744	sql calculating averages	select t.districtname, t.townname, t.cropname, avg(t.pest) from (     select districtname, townname, cropname, cast(pests as float) as pest     from [dw_staging].[dbo].[stagingtable] ) as t group by t.districtname, t.townname, t.cropname go 	0.037811514884361
20165847	25027	order by distance to another value	select * from table order by abs(value - 30) asc 	0.00302445136092268
20177062	13462	sql joining three tables using inner joins	select a.name,b.manufacturer_id,c.id,c.item_desc  from manufacturers as a inner join  item_manufacturers as b on b.manufacturer_id=a.id  inner join item as c  on c.id=b.item_id 	0.742322781194074
20193098	14710	date range not between a specific date sql server	select personid from <person information table> where personid not in(select personid from <timing information table> where intimestamp=<particular date>) 	0.000511466846250631
20194218	33858	sql join where id equals id and date is greatest	select *  from jobs j, locations l where j.id=l.jobid and l.date = (    select max(date)     from locations l2    where l2.jobid=l.jobid    group by l2.jobid) 	0.00180521944730956
20201367	10581	sql omit columns with all same value	select count(row)=count(distinct b) from my_table 	9.62655475573126e-05
20203750	14630	filling null row values with last non-null values - sql table	select * into #temp from importedsales; ;with cte as (    select productname           , id           , count(productname) over(order by id rows unbounded preceding) as mygroup    from #temp ), getproduct as (     select [productname]            , first_value(productname) over(partition by mygroup order by id rows unbounded preceding) as updatedproductname     from cte ) update getproduct set productname = updatedproductname; select * from #temp; 	0
20218525	14265	mysql sort count into different columns	select hour(startdatetime) as hour,   floor(minute(startdatetime) / 30) as minute,   sum(case when capacity = 1 or capacity = 2 then 1 else 0 end) as capacity1_2,   sum(case when capacity = 3 or capacity = 4 then 1 else 0 end) as capacity3_4,   sum(case when capacity > 4 then 1 else 0 end) as capacity5above from transaction t where startdatetime >= '2013-11-26 00:00:00'   and queuestarttime <= '2013-11-26 23:59:59' group by hour(startdatetime),   floor(minute(startdatetime) / 30) 	0.000295999864905816
20230447	13171	displaying values in the table programatically	select a,    case when (row_number() over (partition by a order by a)) = 1     then 1      else 0    end as b     from test 	0.00565249605637354
20246169	32246	difference between value and avg(value)	select     id,     value,     avgvalue,     avgvalue - value as diff from     table1   cross join     (        select           avg(value) as avgvalue       from           table1     ) t2 where     value < avgvalue 	0.00404814499110485
20247235	1715	access 2010 sql-- using where in on select top subquery field	select d.[company],         sum(d.[spending]) from   [data] as d inner join    (                      select top 10 [company]                      from          [data]                      where         [year] in ("2013")                      group by      company                      order by      sum([spending]) desc               ) as t  on  t.company = d.company where d.[year] in ("2012") group by d.company 	0.700877571440768
20257388	770	getting specific results in output	select p.name, m.mags from people p, peoplewhosub ms, magazines m  where p.portid = ms.line and ms.service = m.scode    and p.portid in (     select line     from peoplewhosub      group by line     having count(*) > 1 ); 	0.0399474526736569
20277790	33720	union with a timediff statement in mysql	select timediff(time2,time1) as diff, t.* from mytable t; 	0.609642277586448
20285232	13106	display data in a table	select     t.c.value('local-name(.)', 'nvarchar(max)') as [user],     t.c.value('(firstname/text())[1]', 'nvarchar(max)') as firstname,     t.c.value('(lastname/text())[1]', 'nvarchar(max)') as lastname,     t.c.value('(hour/text())[1]', 'nvarchar(max)') as hour,     t.c.value('(projectname/text())[1]', 'nvarchar(max)') as projectname,     t.c.value('(sex/text())[1]', 'nvarchar(max)') as sex from @xml.nodes('users/*') as t(c) 	0.00130508802729061
20304478	33877	using sqlite fts3, how to join or nest select statements to get row plus snippet?	select category,        id,        header,        snippet(guidelines) as snip from guidelines where content match 'snail*' 	0.435387247944931
20306850	7811	sql query. return all if column = a particular value	select *  from tab  where name like '%" . $name . "%'   and position = case when " .$var. " = 'ignore' then position else " .$var. "end; 	0.000133903250483826
20319502	8153	mysql query returning duplicate results from inner join	select * from cart_card cc, invoice inv,   (  select * from purchase_card   where id between 26118 and 26620  and invoiceid = inv.id   limit 1  ) prc where cc.cartid = inv.cart_invoice_id and cc.cardemail = 'info@test.com' and prc.invoiceid = inv.id 	0.248531669880888
20326567	37180	append string to the query result	select a = 'rajat' + tableb.a from dbo.b tableb where tableb.b >= (select top 1 c from d order by e desc) 	0.0426175354592045
20330596	34913	sql server: group dates by ranges	select t.range as [score range], count(*) as [number of occurences] from (   select case      when score between  0 and  9 then ' 0-9 '     when score between 10 and 19 then '10-19'     when score between 20 and 29 then '20-29'     ...     else '90-99' end as range   from scores) t group by t.range 	0.0142876574042126
20332483	1916	mysql multiple-part index not filtering data set	select distinct y.school_year  from years y join (     select distinct e.yid, e.year     from events e ) e on e.yid = y.id and e.year = y.year 	0.476193005051052
20348751	11617	sql: count each record, starting with the oldest to newest appointment	select id       ,[date]       ,type       ,row_number() over (partition by id order by [date] ) as seq from  appointment where type = 'post-op' 	0
20362083	35255	filter the data in grid view by using select query	select *  from buser  where (  (id+'' like @id) and (name like '%'+@name+'%') and (email like '%'+@email+'%') ) 	0.102634344149194
20372297	12961	query with joins and null columns	select distinct scene.title,                  staff.job_descr  from   actor         inner join scene                 on scene.id = actor.id_scene         left join staff                on scene.id = staff.ids  where  staff.job_descr is null 	0.44755948868277
20379016	31438	sql self join or other way to retrieve matching rows for specified columns	select s.* from spots s inner join (select stationcode, saleshouse, programname, day, date, timehour from spots group by stationcode, saleshouse, programname, day, date, timehour having count(*) > 1 ) j on s.stationcode = j.stationcode and s.saleshouse = j.saleshouse and s.programname = j.programname and s.day = j.day and s.date = j.date and s.timehour = j.timehour 	0.000223356507652704
20387938	38613	how do you determine the average total of a column in postgresql?	select avg(totalbooks) from  (select count(1) totalbooks from books group by author_id) bookcount 	0
20388890	3369	i want to be able to just list the lowest priced product sold for the day after i do a query	select t1.* from sales t1 join (   select date, min(price) price from sales   group by date ) t2 on t1.date = t2.date and t1.price = t2.price 	0
20396612	23303	insert count n1 and n2 column in select query	select item_name, 'all', count(*)  as quantity from tbl group by item_name union all  select item_name, item_color, count(*) as quantity from tbl group by item_name, item_color 	0.0699799568864138
20397406	26975	mysql select issue ( unique )	select destination  from tablename  group by destination having count(distinct source) = 1 	0.799276637349506
20400737	32001	sql command doesn't return rows	select `user_id`, `car_id`, `ad_id`, `brand`, `model`, `year`, `price`, `mileage`, `gearbox`, `status`, `color_in`, `color_out`, `body`, `fuel`, `about`, `main_photo` from `ads` natural left join `cars` natural left join `ad_extras` where `ads`.`user_id` = '2' 	0.16619709247035
20403938	23254	combine between in and like in a request mysql	select u.* from users u inner join cities c on u.location like concat('%',c.name,'%') 	0.158626294972637
20404492	40511	sql where clause where date like mm:ss is defined only	select t.id, t.timestamp  from tablet as t where extract(hour from t.timestamp) = 0   and extract(second from t.timestamp) = 0 	0.770288395698502
20407920	33878	sort the order of "order by" query	select     ticket_item_id,     ticket_item_desc  from ticket_item inner join menu_category on menu_category.category_name=ticket_item.ticket_print_cat where     ticket_item.ticket_id = 1  group by ticket_print_cat order by menu_category.button_sort 	0.0498611402789376
20414624	25873	how would i do a yes/no type sql query?	select        e.firstname,        e.lastname,        case when s.empl_id is null then 'no' else 'yes' end as iss    from       employee e          left join supervisor s             on e.empl_id = s.empl_id 	0.731174579746668
20424461	37173	order by, group by, first result in hql (convert from oracle sql)	select table_num, event_type et from room_history where id in (select max(id) from privacy_history group by msisdn); 	0.0372735994434588
20430039	16438	using inner join on two tables with foreign key that references primary id on main table	select * from modelstable mod inner join brandstable bra on mod.id= ( select id from bra where carbrand='ford') 	0
20430198	5610	replace empty/null string with result from another record	select   iif (     nz(translation.text,"") = "", default.text, translation.text) from    translations as translation,   translations as default,    progdata where   translation.tag="prog_" & progdata.id   and    default.tag="prog" & progdata.id   and   translation.languageid=1    and    default.languageid=2 	0.000536802167557078
20436265	667	mysql group by and select group by	select distinct     orders.*,      sum(if (orders.price_type = 1, products.price * orders.quantity, products.discount_price * orders.quantity)) as subtotal from     orders left join     products on     orders.product_id = products.id group by      order_id 	0.232026686057395
20439260	25680	select n rows and return a row	select group_concat(day,'|') from your_table 	5.16463501115816e-05
20462363	2635	how to join a table containing 2 or more foreign key columns referring to same primary key column in another table?	select t1.emp_name,         t2_lpt1.location,         t2_lpt2.location  from   table1 t1         inner join table2 t2_lpt1                 on ( t1.lpt1 = t2_lpt1.code )         inner join table2 t2_lpt2                 on ( t1.lpt2 = t2_lpt2.code )  where  t2_lpt1.code != 33         and t2_lpt2.code != 33         and ( ) 	0
20477391	1761	optimize select in select	select items.* from items  inner join tags_relationships r1 on (r1.post_id = items.id) inner join tags_relationships r2 on (r2.post_id = items.id) inner join tags t1 on (t1.tag_id = r1.tag_id) inner join tags t2 on (t2.tag_id = r2.tag_id) where      t1.name = 'white' and t2.name = 'bike' and items.status = 'publish'  order by id desc 	0.650680896244366
20477609	13364	identifying percentage in fact table	select homeregion, currentregion,  count(*) / count(*) over () as overall_share, count(*) / count(*) over (partition by homeregion) as homeregion_share,      from     (select c.homeregion, r.regionname as currentregion, c.customerid as cust     from dbo.facttable ft      inner join dbo.customer c         on ft.customerid = c.customerid     inner join dbo.mytime mt         on ft.timeid = mt.id     inner join dbo.regions r         on ft.regionid = r.regionid     where mt.myhour = '09'     group by c.homeregion, r.regionname, c.customerid) uni_users     group by homeregion, currentregion 	0.0109224748084058
20487401	14371	how to add two query results as a single result in sql?	select          invoiceid,          poscode,          cquantity,          cprice,          tcost,          amountpaid,          (select sum(totalcharge) from invoicecharge ic where ic.invoiceid = id.invoiceid) as totalcharge  from invoicedetail id 	0.0028731939889083
20492069	34260	mysql query - pairs of repeating numbers	select no_1, no_2, count(*) as numbercount from sometable group by no_1, no_2 order by numbercount desc 	0.00192183310011249
20494938	10677	sql query with max() and sum() aggregates	select selection1.shopid,accountid,amount   from (select sum(ordertotal) as amount, shopid, accountid from transactions group by     shopid, accountid )  as selection1   inner join (     select max(selection2.amount) as maxofamount, selection2.shopid     from (select sum(ordertotal) as amount, shopid, accountid from transactions group by shopid, accountid )  as selection2     group by selection2.shopid ) max_amount on     max_amount.maxofamount=selection1.amount and     max_amount.shopid=selection1.shopid 	0.65863841918965
20495324	40706	is it possible to move the __migrationhistory system table to a new server?	select * into [dbo].[tempmigrationhistory] from [dbo].[__migrationhistory]; drop table [dbo].[__migrationhistory]; exec sp_rename 'tempmigrationhistory', '__migrationhistory'; 	0.0884762538395488
20499776	18794	mysql query to order results by number of votes in another table for the specifc result/row	select content.id, content.type, content.title, content.url, users.username from content  inner join users on content.uploaderuid = users.id  inner join (    select id,count(*) as votecount    from votes      group by id ) v on v.id = content.id where (content.type = 'pic')  order by v.votecount desc 	7.99248556957999e-05
20500231	28854	mysql query - earn over the average salary	select a.personid, a.firstname, a.lastname, b.placeofstudy, c.salary, (select avg(salary) from job) as avgsalary from person a inner join award d on a.personid = d.personid inner join qualification b on d.qualid = b.qualid inner join job c on a.personid = c.personid where placeofstudy = 'oxford brookes'     and c.salary > (select avg(salary) from job) 	0.004834686699273
20508204	21982	mysql: echo out results from table but don't echo out duplicate results?	select m.*,p.* from ptb_messages m inner join ptb_profiles p on p.user_id = m.from_user_id inner join (   select max(id) as id,msg_id    from messages    group by msg_id ) a on a.id = m.id where m.to_user_id = ".$_session['user_id']."   and m.to_user_deleted != '".$_session[' user_id ']."'   and m.from_user_deleted != '".$_session[' user_id ']."'   and m.from_user_id != '0' order by m.date_sent desc 	0
20509347	33600	how to join 3 tables and sum columns with some null values	select        sum(isnull(combo.price, 0)) as expr1, isnull(max(product.price), 0.00) as prodprice from            order left outer join                          combo on order.combo_id = combo.combo_id                 left outer join product on order.product_id = product.product_id                       where        (order.sales_id = @id) 	0.000922661083686577
20513207	9165	mysql, combining distinct and join	select users.*, a.* from users inner join (     select user_id, max(timestamp) max_timestamp     from activity     group by user_id ) x on users.user_id = x.user_id  inner join activity a on x.user_id = a.user_id and a.timestamp = x.max_timestamp order by a.timestamp; 	0.231298552523543
20514847	36783	choosing the right foregin key in sqlite table	select last_insert_rowid() 	0.0911918969846266
20518915	8668	using sum,count on the same column in mysql	select date(datetime),        carpark_name,        sum(case action when '2' then 1 else 0 end) as acceptedimg,        sum(case action when '3' then 1 else 0 end) as rejectedimg,         sum(case action when '4' then 1 else 0 end) as changeimg,          sum(case when action in ('2','3','4') then 1 else 0 end) as review        sum(case action when '23' then 1 else 0 end) as acceptedviolation,        sum(case action when '24' then 1 else 0 end) as rejectedviolation,        sum(case action when '25' then 1 else 0 end) as skippedviolation,        sum(case when action in ('23','24','25') then 1 else 0 end) as contravention from customer_1.audit_trail  inner join customer_1.carparks     on customer_1.audit_trail.location_id =  customer_1.carparks.id where date(datetime) > '2013-12-01'   and date(datetime) < '2013-12-03'     and location_id = '146' group by date(datetime),carpark_name 	0.00273929800925098
20521601	34390	group values matching criteria to single distinct array	select t1 from     (select distinct s.t1       from myobject s       where s.category_id = 1 and s.t1 is not null) as q union  select t2 from     (select distinct s.t2       from myobject s       where s.category_id = 1 and s.t2 is not null) as w union  select t3 from     (select distinct s.t3       from myobject s       where s.category_id = 1 and s.t3 is not null) as e union  select t4 from     (select distinct s.t4       from myobject s       where s.category_id = 1 and s.t4 is not null) as r union select t5 from     (select distinct s.t5       from myobject s       where s.category_id = 1 and s.t5 is not null) as t order by t1 asc 	0.000147221533166725
20524326	10959	sql query with sum and group by	select field1, sum(field2) as field2 from mytable group by field1 	0.49996519320041
20524632	21471	count one table and order by it	select r.rumorid, r.rumor_author, r.rumor_title, r.rumor_text, t.topic_name, a.first_name, a.surname, t.topicid, r.datum_geplaatst, count(c.rumorid) as commentcount  from rumor r  join account a on a.userid = r.rumor_author  join topic t on t.topicid = r.topicid  left join comment c on r.rumorid = c.rumorid  group by r.rumorid  order by commentcount asc 	0.0158198339132259
20542044	31308	write a query to arrange product and category of db table	select p.`id` as "id" , p.`name`as "product name",c.`category`as "category"  from `product` p inner join `category`c on (p.`cat_id`=c.`cat_id`)   order by p.`id` asc 	0.00174048701131869
20542530	30835	add a join in a union query mysql	select as1,as2,as3,as4,y.id_event, pushtoken, phone, name, ai, surname2, y.nif, year, city, status from tablex join (    select id_event, pushtoken, '' as phone, name, surname1 ai, surname2, nif, year, city, status     from signedup where status = 0    union all    select id_event,'' as pushtoken,  phone, name, surname1 ai, surname2, nif, year, city, status     from signeduplocal where status = 0 ) y on tablex.id_event = y.id_event and tablex.nif = y.nif order by ai asc 	0.409135568792525
20544180	26573	select rows between x number and y number	select * from table limit 2000,1000 	0
20546135	28468	mysql difference in two dates with days and minutes result	select   avg(datediff(date2, date1)) days,   sec_to_time(avg(time_to_sec(timediff(date2, date1)))) time from   table 	0
20547897	28791	sys.syscomments.name length > 4,000	select top 100      *  from sys.sql_modules  where 1=1     and definition like '%trigger%' 	0.379741553795227
20559468	12118	sql query and join table	select node_id  from group_nodes where group_id in ($groups) group by node_id having count(distinct group_id) = $arraysize 	0.452773572144102
20562075	6540	get the sum of like values in one column for each value in another column	select user, saletype, count(*) totalsales from sales_record group by user, saletype 	0
20566059	13143	iterating stores over a set of dates	select calendar.date, stores.store, count(t1.transaction_id) as number from calendar, stores left join transactions t1 on t1.date_of_transaction = calendar.date      and t1.store = stores.store group by calendar.date, stores.store 	0.0158921567025927
20568061	34641	most common value	select author  from table  group by author  order by count(*) desc  limit 1  	0.000540894093397911
20569594	31863	php - mysql: get rows from table where date between two dates	select * from your_table where month(str_to_date(res_birthday, '%d.%m.%y')) = 1 and dayofmonth(str_to_date(res_birthday, '%d.%m.%y')) between 1 and 10 	0
20572300	15193	can't execute query: bigint unsigned value is out of range	select * from user where hide_time > 0 and hide_time < 10 	0.152228608907928
20576741	9955	remove certain words from mysql result	select name,email from users where email not in (select email from email_logs); 	0.000241372297243578
20582763	5197	sql query to select all sub folders	select * from folderfolder ff  inner join folderfolder ff_child on ff_child.parentfolderid = ff.childfolderid inner join folder f on f.folderid = ff.childfolderid or f.folderid = ff_child.childfolderid where ff.parentfolderid='112' 	0.156446838119394
20593920	2170	sql query for extracting info from one table based on other	select cities.cityname, countries.countryname from cities inner join countries on countries.country_id = cities.country_id order by countries.countryname, cities.cityname 	0
20618930	18474	selecting from a table based on a distinct column	select      max(id) as id,      pro  from prolookup  where pro like '%" & replace(q,"'","''") & "%'" group by pro 	0
20634838	33929	sum from different fields in different mysql tables	select al.uid as uid , sum(al.points) as total_points from (select points, uid from table1                              union all           select points,uid from table2) al group by al.uid 	5.99930727799223e-05
20639154	3976	oracle select twice in the same table without duplicates	select t.a, t2.a from table t, table t2  where t.a < t2.a and <old_condition> 	0.00197771470084088
20643718	33285	join for more than one table	select distinct c1.organizationname, c2.assetnumber, c3.ipaddress from organization c1 inner join product c2     on c1.organizationid = c2.organizationid inner join ipaddress c3     on c2.productid = c3.productid where c1.organizationname = 'orgname' 	0.0208334192218032
20656240	11836	how to concatenate one to many records in sql server	select userid,     stuff((select ',' + t2.rolename      from userroles t2 where t1.userid = t2.userid      for xml path('')),1,1,'') roles from userroles t1 group by userid 	0.000257953011018506
20665237	9770	another sql max/count qestion	select rs.a_id, rs.s_id, count(rs.s_id)  from result_set rs inner join      (select p_id, a_id, max(t_id) t_id from result_set group by p_id, a_id) x on rs.p_id=x.p_id and rs.a_id=x.a_id and rs.t_id = x.t_id inner join people p on p.p_id = rs.p_id where p.p_gen = @gender_variable and not rs.s_id = 0 group by rs.a_id, rs.s_id 	0.366318031242287
20668988	35829	how do you find your user name from a mysql prompt?	select user(),current_user(); 	0.00299030818680158
20676913	40744	needing assistance with counting the most different books	select c.cust_id, count(distinct od.book_id) bookcnt from a_bkorders.customers c  inner join a_bkorders.order_headers oh on c.cust_id = oh.cust_id  inner join a_bkorders.order_details od on oh.order_id = od.order_id  group by c.cust_id order by bookcnt desc 	0.0130120457268433
20678754	27926	compare two last rows values	select sum(case when rnum = 2 then -1 * value else value end) diff_value,        round(sum(case when rnum = 2 then -1 * value else value end) /              sum(case when rnum = 1 then 0 else value end) * 100) diff_percent   from (   select quarter, value, @n := @n + 1 rnum     from table1 cross join (select @n := 0) i    order by quarter desc    limit 2 ) q 	0
20680415	6538	map values to text "on fly"	select store, (case dow when 1 then 'sunday'                          when 2 then 'monday'                          when 3 then 'tuesday'                          when 4 then 'wednesday'                          when 5 then 'thursday'                          when 6 then 'friday'                           when 7 then 'saturday'                end), turnover  from tablea; 	0.00952070323164598
20685407	38052	displaying records with a date at least one day greater then or = to today	select <something> from table where datef >= convert(date,getdate()) 	0
20686330	14593	retrieve count from sql join query	select table.productid, sum(product.weight) weight from table1       inner join product       on table1.productid=product.productid where table1.box = '55555' group by table.productid 	0.0152744776525699
20694782	18049	select x from table where	select distinct user.name from store join user on store.id = user.id where active = true 	0.00283700291404295
20702680	25968	xmlelement() function not recognize the value of variable as tag name	select (xmlelement(evalname(l_ii), null) ||'')    into l_temp    from dual; now, i am getting output like :<a-ani-ii/> 	0.238836567992149
20708951	16226	case on join criteria possible	select     case when m.current0 < 25000 then 'limited' else 'unlimited' end     ,m.current0 as currentbalance     ,m.status as currentstatus     ,sh.datechanged as entertedpa6     ,datediff(d, sh.datechanged, getdate()) as dayspassed  from statushistory sh     inner join master m on m.number = sh.accountid and sh.newstatus = m.status            where m.status = 'pa6' and m.state = 'ca' and     ((m.current0 < 25000 and sh.datechanged <= dateadd(day, -20, getdate()))      or (m.current0 >= 25000 and sh.datechanged <= dateadd(day, -90, getdate()))) 	0.734580674169596
20712713	15503	adding count(*) from a join to a query	select profiles.photo, postings.postid, postings.text, postings.date, members.fname,members.lname, members.userid,  likes.like_count  from profiles, members, postings  left join (select post_id, count(*) like_count from likes group by post_id) as likes       on postings.postid=likes.post_id  where postings.wallid=postings.posterid   and postings.wallid=members.userid   and postings.wallid=profiles.userid 	0.0476750878600601
20725581	28194	how to list all the roles existing in oracle database?	select * from dba_roles; 	0.00032389915464848
20725947	23506	mysql table.* as reference	select table.id as table_id, table.title as table_title,        table2.id as table2_id, table2.title as table2_title from . . . 	0.105144424576757
20746157	19076	php mysql select alias automatically all fields in a table?	select concat('tablea.', column_name, ' as tablea_', column_name, ', ') from information_schema.columns c where table_name = 'tablea'; 	0.00841586306525629
20751291	23448	webmatrix - sql query relationship	select * from 'property table' props left join 'images table' imgs on imgs.propertyid = props.propertyid 	0.431367219947616
20779832	8205	how to find best match from the left in mysql	select *   from table1  where str_col like 'fr10%'     or str_col like 'fr1%'     or str_col like 'fr%'     or str_col like 'f%'  order by 4 * (str_col like 'fr10%') +           3 * (str_col like 'fr1%') +           2 * (str_col like 'fr%') +           1 * (str_col like 'f%') desc,           char_length(str_col),           str_col 	0.00267655525285723
20780210	16807	sql query - multiple rows for each object	select a.id, a.color, b.id from   a join b on a.id = b.a_id where a.id in (select id from a order by color limit 2) order by a.id 	0.000891088677898891
20789603	9150	combine multiple varchar rows into one	select a.col1,        min(col3) col3,        min(col4) col4 .... from gcl_blackboard a left join gcl_investors b on a.adjective_id = b.investor_id left join gcl_loan_programs c on a.adjective_id = c.program_id left join gcl_loan_purposes d on a.adjective_id = d.purpose_id group by a.col1 	0.000116022492842797
20796275	25151	table definition of user type	select *     from sys.columns     where object_id in (       select type_table_object_id       from sys.table_types       where name = 'some_table_type'     ); 	0.0219947917114372
20808003	22016	ssrs r2- compare single values in multi value parameters	select *  from table_name  where (country in (@country))          |                     |              |                     |       \                     /        \                   /           these extra two parenthesis does the trick when we have a multiple value           parameter. 	0.00548830109401237
20811415	2297	how to get last auto increment value in a table? vb.net	select max(id) from mytable 	0
20815303	21556	get the average of a column made by group by date()	select count(time) / count(distinct date(time)) from  tablename where date(time) between '2013-07-14' and '2013-12-23'; 	0
20829864	15962	multiple foreign keys from a column to a table	select t.id, s1.name as showstate, s2.name as ticketstate   from ticket as t   join ticketstate as s1 on t1.showticketstateid = s1.id   join ticketstate as s2 on t1.ticketstateid     = s2.id 	0
20850525	9343	mysql : select count when id have multiple same value	select id, count(object) from tablename group by id 	7.93330347462575e-05
20855708	830	get unique data from table	select empname,        deptid,        min(empid) as empid        from  dbo.sample  group by empname, deptid 	8.70718273404515e-05
20856344	5790	select only same values as other row has	select sports.sportid, sport from   sports join   userssports on     sports.sportid = userssports.sportid where  userssports.profileid = '1003' and exists     (select 1       from   userssports as otheruser      where  otheruser.profileid != '1003'        and    otheruser.sportid = sports.sportid     ) 	0
20881357	28973	php or mysql - how to display only one table row out of many with the same value	select distinct substring(name,1,1) from company order by substring(name,1,1) 	0
20882492	27751	mysql rows connection	select p.id as 'id', p.added as 'added', p.quant as 'quant', pn.name as 'name',        max(if(pf.feature_alias = 'color', pf.feature_value_name, null)) as 'color',         max(if(pf.feature_alias = 'sex', pf.feature_value_name, null)) as 'sex',        max(if(pf.feature_alias = 'size', pf.feature_value_name, null)) as 'size' from product p inner join product_names pn on p.id = pn.product_id and pn.lang = 'en' inner join product_types pt on pt.type_alias = p.type_alias and pt.lang = 'en' inner join product_features pf on pf.product_id = p.id and pf.lang = 'en'  where pt.type_alias = 'shirts' group by p.id 	0.0735257362046526
20909492	17410	mysql not showing databases created in phpmyadmin	select user(); 	0.774123489653944
20930500	12847	find data within specific dates?	select *  from (     select employeenumber, count(1) as totalamountofvisitor      from x      where visitdate between '2010-01-01' and '2010-01-31 23:59:59'     group by employeenumber ) as reftable inner join y on reftable.employeenumber = y.employeenumber 	0.000425443067678375
20931375	19138	select count in cycle	select n.name, n.text, count(c.news_id) total_comments   from news n left join comments c      on n.id = c.news_id  group by n.id 	0.124481239379489
20938308	15000	read a list of values from another table using subquery and check where in condition	select distinct c.* from customers c join users u on find_in_set(c.id, u.assigned) is not null 	0.000150326119076369
20940060	29612	sqlite - selecting based on percentage of total	select id from my_table where ip in (select ip from my_table where id in (1, 2, 3, 4)) group by id having sum(count) >= (select 0.1 * sum(t.count) from my_table t where t.id = my_table.id) 	0
20945402	11633	how to get the sum?	select call_type, channel   , sum(case when status='no answer' then 1 else 0 end) as cnt_no_answer   , sum(case when status='answered' then 1 else 0 end) as cnt_answer   , count(status) as cnt_all_stated   , count(*) as cnt_all_records from app_account.cc_call group by call_type, channel; 	0.00420814632954591
20946509	3289	how to merge two aggregate functions in sql server	select      replace(convert(varchar(8), sysdatetime(), 3), '/', '') +      right('0000' + cast((count(sno)+1) as varchar(5)), 5) from tbl_demographic_reg 	0.288421859371584
20952720	9814	fetching data from multiple tables mysql?	select u.id, u.username, up.email,        sum(if(p.direction = 'payin', p.amount, 0)) as payin,        sum(if(p.direction = 'payout', p.amount, 0)) as payout,        sum(p.direction = 'payin') as payin_count,        max(if(p.direction = 'payin', p.time, 0)) as payin_maxtime from users as u join userprofiles as up on u.id = up.user_id join payments as p on u.id = p.user_id group by u.id 	0.00314875200454632
20961212	31293	how do i attain the item in the column "street number" alongside the minimum value from "occupants"?	select *  from   book b1  where  b1.occupants = (select min(b2.occupants)                         from   book b2) 	0
20967748	30805	mysql how to query complex relational tables	select article.title from article_subject     left join article using (article_key)     left join subject_catalog using (index_key)     left join subject_catalog sc2 on subject_catalog.index_key = sc2.rt_key where subject_catalog.subject like 'milk%' or sc2.subject like 'milk%' 	0.757474436975978
20968276	36604	sql to find the matching row between two tables of same schema	select  max(match)  from  ( select  case when x_staging.key_id='key_from_the_first_row_of_x' then rownum else 0 end as match  from  x_staging  ) 	0
20969894	18130	finding common rows with sql	select $select_string  from users_groups ug  inner join groups g on g.group_id = ug.ug_group_id where ug.ug_user_id in ($user_id1, $user_id2) group by g.group_id having count(distinct ug.ug_user_id) = 2 limit 10 	0.00150295224094
20972119	4175	mysql query, how can i get top 5 downloads with group_concat	select brand_id, group_concat(image_id) image_ids from (select brand_id, image_id,               if(@lastbrandid = @lastbrandid:=brand_id, @idx:=@idx+1, @idx:=0) rownumber        from table1, (select @lastbrandid:=0, @idx:=0) a       order by brand_id, downloads desc      ) as a where rownumber < 5 group by brand_id 	0.0535119345667809
20996048	5887	mysql- sorting varchar column includes number and char	select id      from test order by (case when id regexp('(^[0-9]+$)') then 0 else 1 end),           cast(id as unsigned),           id 	0.00691545704186115
21004149	20651	how to show different dates data (from the same table) as columns in oracle	select condition, count(case when to_date(xdate) = to_date(sysdate) then 1 end) to_day,        count(case when to_date(xdate) < to_date(sysdate) then 1 end) last_7_days   from my_table  where to_date(xdate) >= to_date(sysdate) - 7  group by condition 	0
21015762	26913	sql not selecting multiple rows based on a value in one of them	select * from table where name not in (select name from table where action = 'void') 	0
21027315	13566	sql - select top cities based on population per country	select * from   ( select country          ,      city          ,      population          ,      rank() over (partition by country order by population desc) position          from   cities        ) v where  position <= 10 	5.78099232001355e-05
21035924	18203	access - sql query -> find most recent record and save it to a table	select top 1 *  from tblhistory a inner join     (select unit number, max([date]) as maxdate      from tblhistory     group by unit number) b on a.[unit number] = b.[unit number] and a.[date] = b.maxdate 	0.000152599624282563
21037578	14952	mysql hamming distance between two phash	select product_id, bit_count(phash ^ 'phashfromuserinput') as hd from a order by hd asc; 	0.0153367471737395
21051452	31627	inner join but i don't understand the foreign key bit with a nother table	select r.reviewid, r.reviewtime, r.reviewdata, p.name, u.firstname, c.categoryname from review r left join product p on p.productid = r.productid left join user u on u.userid = r.userid left join category c on c.categoryid = p.categoryid 	0.0191622521909057
21054409	18949	mysql group by in desc order	select m.* from tbl_messages m join      (select conversation_id, max(msg_id) max_msg_id       from tbl_messages       group by conversation_id      ) mc      on m.msg_id = mc.max_msg_id; 	0.51295205438958
21059114	845	sql - date range return all data	select emp_id,emp_name,date1,( case when exists( select emp_id from timesheet_tran at where t.emp_id =at.emp_id and t.date1=at.date ) then 'present' else 'absent' end )as status from ( select emp_id ,emp_name,cast(date as date)as date1 from emp_master a,(select distinct date    from timesheet_tran ) b ) t 	0.000145606562774432
21062908	11955	multiple join on query	select c.id,    cm1.meta_value as name,   cm2.meta_value as email,   cm3.meta_value as bussiness_phone from contact as c left join contact_meta as cm1 on cm1.contact_id = c.id and cm1.meta_key = 'name' left join contact_meta as cm2 on cm2.contact_id = c.id and cm2.meta_key = 'email' left join contact_meta as cm3 on cm3.contact_id = c.id and cm3.meta_key = 'bussiness_phone' order by c.id desc 	0.419262348174567
21084980	22085	mysql count combination of non unique data in row	select count(*) from (  select tid,    sum(case         when `data` like '%c%' then 1         when `data` like '%f%' then 1         else 0         end    ) as freq  from `table`  group by tid  having freq = 2 ) t 	8.58984277848873e-05
21101221	34247	conditional query to determine the status of my reports	select reports.report_id ,case when exists(select * from approvals denied where                 denied.report_id = reports.report_id                and denied.status = 3)then   'denied' when (select count(approvals.report_id))=0 then   'draft' when (select count(approvals.report_id))<>5 then   'pending' when (select count(approvals.report_id))=5 then   'approved' end from reports left outer join approvals   on reports.report_id = approvals.report_id group by reports.report_id 	0.134208730377392
21107987	6022	show grouped by items in comma separated format	select continentid, countryid,       statecode =          stuff((select ', ' + statecode            from location b             where b.continentid = a.continentid                 and                 b.countryid = a.countryid            for xml path('')), 1, 2, '') from location a group by continentid, countryid 	0
21113903	36141	timestamp gives false result	select stamp, p1.id,  p1.status from `proba` p1  inner join (    select max(timestamp) as stamp from `proba` group by id  ) p2 on p1.timestamp = p2.stamp 	0.193274138135308
21115146	14700	ensuring only distinct records are returned with distinct	select  t.date_field_one, t.date_field_two, t.arbitrary_value from (  select  date_field_one,                  date_field_two = min( date_field_two )         from    dbo.[table]         group by date_field_one ) dl left join dbo.[table] t     on  dl.date_field_one = t.date_field_one     and dl.date_field_two = t.date_field_two; 	0.000184731588917166
21124568	11902	query not returning the right rows	select *  from `messages`  where   (           (`sender_id` = '111' and `recipient_id` = '222')      or (`sender_id` = '222' and `recipient_id` = '111')    )   and (`is_message` != 'on' or `is_message` is null)   and (`mass_message` != 'on' or `mass_message` is null)   and `invite_for_lunch` = 'on' limit 0 , 30 	0.500041904752274
21134061	30351	how to select columns with aggregate function sql server	select sum(convert(float, replace(total, char(0), ''))) as total, [product name]   from tb_sales_entry_each_product group by [sales date], [product name] 	0.569461274120263
21143129	36629	calculating totals by group	select *,        sum(thisnumber) over (partition by procedureid) from barrevenuebyprocedurepriceinfo where deptid = '010.4730' and segmentdatetime = '2013-11-30 00:00:00.000' order by procedureid 	0.0877820262176657
21147796	25505	sum total of table with two related tables	select name, ifnull(f.total, 0) as total_fruit, ifnull(c.total, 0) as total_cookie from person as p left join (select person_idperson, sum(cost) as total            from fruit            group by person_idperson) as f on p.idperson = f.person_idperson left join (select person_idperson, sum(cost) as total            from cookie            group by person_idperson) as c on p.idperson = c.person_idperson 	0
21165635	11856	join 3rd table in mysql	select    coll.title as collectiontitle,    cont.collectionid,    cont.title as containertitle,    cont.id as containerid,    cont.levelcontainerid,   cont.contentid,   user.title,   user.value,   user.eadelementid  from tblcollections_content cont  join  tblcollections_collections coll    on cont.collectionid = coll.id  join tblcollections_userfields user   on cont.contentid = user.contentid where cont.title is not null  order by collectionid, containerid 	0.140127797704054
21167625	26262	key-value-pair, column for each key, keys as columnheader	select object_id, max( if( field_key = 123, field_content, null) ) as col_123, max( if( field_key = 234, field_content, null) ) as col_234, max( if( field_key = 345, field_content, null) ) as col_345, max( if( field_key = 456, field_content, null) ) as col_456, max( if( field_key = 567, field_content, null) ) as col_567 from field_list group by object_id 	9.60988936818486e-05
21189347	28986	how to change some of the fields for the table in the form to display other fields in other table?	select appointmentid    ,adate    ,atime    ,astatus    ,acontact    ,aheight    ,aweight    ,p.pfirstname    ,m.mccentre    ,n.nfirstname        from appointment as a left outer join nurse as n  on a.nurseid = n.nurseid left outer join patient as p on a.patientid = p.patientid left outer join medicalcentre as m on a.mcid = m.mcid 	0
21193858	29691	sql grab duplicate record with same second column	select ub.id, ub.brokerid, ub.userid from userbroker ub inner join userbroker mub  on ub.brokerid = mub.brokerid  and ub.userid <> mub.userid group by ub.id, ub.brokerid, ub.userid order by ub.brokerid, ub.userid, ub.id 	0
21195582	25659	sum on subqueries on sql server	select id, col1, col2, [total] = (col1 + col2) from (     select id,     (select count(*) from table1 left join table2 on ...) as col1,     (select count(*) from table3 left join table4 on ...) as col2     from [table]) t 	0.472352766978094
21219634	13515	mysql joining sharing data between tables	select * from bands left join orders as user_orders on( user_orders.band_id = bands.band_id and user_orders.user_name = "'.mysql_real_escape_string($user_name).'" ) 	0.00313207569735275
21235853	33526	get count of rows where user id w.r.t to sender	select  least(sender, receiver) as x,  greatest(sender, receiver) as y,  count(1) from  tbla group by  x, y; 	0
21239754	18736	sqlite memory usage in c#	select * from .. 	0.760239012419607
21252187	8820	mysql query get result by month and year	select id,month_month,month_year where (month_month >= 10 and month_year = 2012) or      (month_month <= 10 and month_year = 2013) 	0.00016540740053762
21254849	20975	verify that set foreign key checks is set to = 1	select @@foreign_key_checks; 	0.000152809376917833
21264984	2687	output sql query to a variable then create a new query	select u.*  from dbo.usermailbox u     inner join dbo.adusers a on u.linkedaccount = a.upnprefix 	0.151497755639658
21278542	21374	mysql: group by austral year?	select avg(`value`) from tablename group by year(`date` + '6 months'); 	0.0363212462275768
21281576	2818	conversion from date format in sql server 2005	select convert(varchar,dateadd(d, 1,convert(datetime, '20140121', 112) ),112) 	0.109807765897919
21284420	36529	getting a column of data from a different table mysql	select     x.id,      x.site_id,      x.notes,      y.name from     x     left join y on x.site_id = y.site_id 	0
21293986	5103	need assistance in creating query to sum up number of occurrences in a table	select t1.uid, t1.event, count(*) as `# event used`, t2.total_events as `# of sessions for uid` form table t1 inner join (    select uid, count(*) as total_events    from table    group by uid ) t2 on t2.uid = a.uid group by t1.uid, t1.event, t2.total_events order by t1.uid, `# event used` desc 	0.0438002404478917
21304424	22386	join string and add character between them in mysql	select    a.name,   group_concat(s.name separator '|') store_name from   agents a    join stores s      on (a.id = s.agent_id)  group by a.id 	0.0095737474142394
21308918	27275	php selects the same rows from different process	select ... for update 	4.91654515418606e-05
21318947	21785	treat missing rows as having 0 data	select w.worker, avg(coalesce(t.relative, 0.0)) as avg_rel from (select distinct project from my_table) p cross join      (select distinct worker from my_table) w left outer join      my_table t      on t.project = p.project and t.worker = w.worker group by w.worker; 	0.0313367352788499
21319777	11849	optimal lookup table query for multiple products?	select size_id, sum(if(color_id=1,price,0)) c1, sum(if(color_id=2,price,0)) c2, sum(if(color_id=3,price,0)) c3, sum(if(color_id=4,price,0)) c4 from table group by size_id 	0.0687589799346072
21329608	29029	group concat between two tables	select group_concat(distinct a.associated_project_basic_information_id) as project_basic_information_ids  ,        group_concat(distinct b.title) as project_titles  from map_associated_projects a   left outer join project_basic_information b on a.associated_project_basic_information_id = b.project_basic_information_id  where a.project_basic_information_id = 'pbid_1' group by a.project_basic_information_id 	0.0144594624434327
21329631	22222	how to write sql statements in php?	select * from students 	0.753066749646532
21330736	6803	computing division between the number of rows of two tables in sql server	select round( (select count(*) from   a)              / (select count(*) from   b), 1) as final 	0
21334537	37238	getting single records from multiple rows by id in one column	select p_id from activitiesperperson  where activity_id in (53, 65, 510) group by p_id having (   sum( case when activity_id = 53 then 1 else 0 end ) > 0   and   sum( case when activity_id = 510 then 1 else 0 end ) > 0 ) or (   sum( case when activity_id = 65 then 1 else 0 end ) > 0   and   sum( case when activity_id = 510 then 1 else 0 end ) > 0 ); 	0
21348700	3785	select top records from multiple entries	select id,user,cmd,max(ts) ts from `logins` group by user 	0
21353831	22244	mysql most recent n entries, ascending?	select * from (select owner_id,message,time  from messages where thread_id = ?  order by time desc limit ?) test order by time asc 	0
21357012	17232	trying to get 2 sums within one table with addition of a join	select a.username, b.type, sum(case when b.type = 'tip' then 1 else 0 end) as "tipscount", sum(case when b.type = 'request' then 1 else 0 end) as "requestscount" from users as a left join submissions as b on a.id = b.user_id  group by a.username, b.type; 	0.000183458279585773
21360747	33707	postgres strings comparison peculiarity	select '.0' < '00', '.9' < '00', '.9' < '00' collate "c";  ?column? | ?column? | ?column?   t        | f        | t 	0.404894409486627
21373919	8196	how to fetch unique values from two tables in sql?	select * from ( select *,row_number() over(partition by addrid order by addrid asc) as rn  from table1       join table2 on      table1.addrid =table2.addrid ) as t where rn = 1 	0
21374421	1232	select records between two months with year difference	select * from tbl  where userid=1 and str_to_date(concat(fldyear,'-',lpad(fldmonth,2,'00'),'-',lpad(fldate,2,'00')), '%y-%m-%d') between str_to_date(concat(2012,'-',lpad(03,2,'00'),'-',lpad(01,2,'00')), '%y-%m-%d') and  str_to_date(concat(2013,'-',lpad(06,2,'00'),'-',lpad(01,2,'00')), '%y-%m-%d'); 	0
21384423	28638	oracle - how to join in this situation [other option other than join]?	select (case when t.seqnum = 1 then t.id else '0' end) as id,        (case when t.seqnum = 1 then t.start else t."end" end) as timestamp,        t.unit,        t2.unit_description from (select t.*,              row_number() over (partition by id, unit order by start) as seqnum,              count(*) over (partition by id, unit) as cnt       from table t       ) t join      t2      on t2.unit = t.unit where seqnum = 1 or seqnum = cnt; 	0.773357534090224
21401528	9636	compare the starttime and endtime of a newly creating event with existing events of same time on same day?	select @count = count (eventid) from tblevent where (('@starttime'  between starttime and endtime) or ('@endtime' between starttime and endtime));   if @count = 0     begin     select @count = count (eventid) from tblevent where (('@starttime' < starttime and '@endtime' > endtime));     end         if @count > 0              begin                 select 'event is already exists at that point of time please select another time ' as 'message';                 end     else     begin         select 'event is added' as 'message';        end 	0
21417441	17569	how to select distinct with an order by and for xml in sql server 2008+	select stuff ((   select cast('/' as varchar(max)) + location      from locations      group by location      order by max(time) for xml path('')) , 1 , 1 , '' ) as result 	0.425146322854335
21422074	22338	sqlite with inner select	select * from eventinfo      where name like "%search text%" or            description like "%search text%" or            _id in (select parenteventinfoid from eventinfo                    where (name like "%search text%" or                            description like "%search text%")  order by sortid 	0.729479196069665
21428520	5038	running a nested sql query to subtract the result of the latter select query	select max(result, 0) 	0.178704610722862
21435011	35290	select the first occurence in a table in hive	select s.id as id, s.msts as msts, s.action as action from (   select min(named_struct('msts', msts, 'id', id, 'action', action)) as s   from a group by id ) t; 	0.00130285551271643
21436182	41246	scan entire db programatically	select o.name,   ddps.row_count  from sys.indexes as i   inner join sys.objects as o on i.object_id = o.object_id   inner join sys.dm_db_partition_stats as ddps on i.object_id = ddps.object_id   and i.index_id = ddps.index_id  where i.index_id < 2  and o.is_ms_shipped = 0 order by o.name 	0.262474564789493
21436434	4189	how do i cross-join a table with a list?	select a.*, b.val from a lateral view explode(array(1,2,3,4)) b as val; 	0.0408755463472384
21437256	37269	need to know how to sql query where all a like model numbers differs in description	select *   from test where   model_number in (     select model_number       from test   group by model_number     having count(distinct description) > 1) 	0.0800423608816544
21437656	2944	how to get the date from a varchar	select convert(date, case when isdate(substring(data, 8, 17)) = 1                           then substring(data, 8, 17)                           else null end)  from mastinfo 	0.000112566851723061
21449519	19688	return the sum of counts from multiple years	select decadestart, max(moviecount)      from (            select m.year as decadestart, (                select count(*)                from movie m2                where m2.year >= m.year and m2.year < (m.year + 10)                 and m2.year is not null)            as moviecount           from movie m group by m.year           ) movie ; 	0
21449954	21980	how to compare time and date columns together in mysql?	select a1.event_id,         min(concat(a2.event_date, ' ', a2.event_time)),         max(concat(a2.event_date, ' ', a2.event_time))  from   event_log a1         inner join event_log a2                 on a2.event_id = a1.event_id  group  by a1.event_id 	0.000250126258934258
21457525	16755	how to find rows with the sequence of values in a column using sql?	select first_name, work_date, work_hours from (   select first_name, work_date, work_hours     , lag(work_hours) over (order by first_name, work_date) as prev_work_hours     , lead(work_hours) over (order by first_name, work_date) as next_work_hours   from person ) where (work_hours = 0 and next_work_hours = 1) or (work_hours = 1 and prev_work_hours = 0) order by first_name, work_date; 	0
21459179	5326	find two table where one table has redundant value	select * from job_list as jl left join user_list as ul on ul.user_id = jl.user_id where ul.user_id is null 	0
21471357	41180	summary of log types per day	select date(logtimestamp) as logdate,     sum(level = 'error') as error_qty,     sum(level = 'warning') as warning_qty,     sum(level = 'info') as info_qty,     sum(level = 'ok') as ok_qty from tbl_logs group by logdate order by logdate desc 	8.46682418347957e-05
21476431	38588	mysql select first 5 rows (multiple rows)	select feld1,feld2 from ( select feld1,feld2 from table1 where... limit 1,1 union all select feld1,feld2 from table2 where....limit 2,1 .... )a limit 5 	0
21476738	2506	case-based query	select id,description,        case when grade1 is not null then 'excellent'             when grade2 is not null then 'good'             when grade1 is null and grade2 is null then 'average'             else ' '        end [grade] from table1 	0.46185082725027
21506797	21753	sql, using data from a number of separate tables to receive an output	select b.title from book b join      author a      on b.bookid = a.bookid join      writer w      on w.authid = a.authid join      publisher p      on w.pubid = p.pubid where p.country like 'australia' group by b.title, b.bookid having count(*) >= 2; 	5.45999081323368e-05
21509209	35605	sql how to add all fields with the same field value and order it by descending order	select   field1, sum(field2) as total  from     table1  group by field1  order by sum(field2) desc 	0
21514923	38126	sql server ce cast a date field	select   convert(varchar(10), entered, 101) as [date]          , item_assigned        , count(*) as total from     datasheet group by convert(varchar(10), entered, 101), item_assigned 	0.344300508774866
21520038	2246	find max and second max salary for a employee table mysql	select   (select max(salary) from employee) maxsalary,   (select max(salary) from employee   where salary not in (select max(salary) from employee )) as [2nd_max_salary] 	0
21525116	25390	how to write this query from 2 tables	select empid,empname, salary, grp.groupname from employee emp left outer join  groupname grp  on ( emp.age > grp.[min] and emp.age < grp.[max]) 	0.150380072298772
21540782	35224	sql server - list the number of occurrences for specific strings within a column	select n.name, count(*) from table t join      names n      on ','+t.resource_list+',' like '%,'+n.name+',%' group by n.name; 	0
21545858	18324	compare nth row with n+1 th row and if it lies in range of n th row print n+1th row usng oracle query only	select b.id  from   iv_stock_details a,         iv_stock_details b  where  a.id + 1 = b.id         and b.stock_stat_no >= a.stock_stat_no         and b.stock_stat_no < a.stock_end_no         and b.stock_end_no <= a.stock_end_no         and b.stock_end_no > a.stock_stat_no; 	0
21548700	37178	select 2 counts from a join query	select lists.*,         count(distinct lists_account_assignment.id) as num_of_accounts,         count(distinct lists_user_assignment.id)    as num_of_users  from   lists         left join lists_account_assignment                on lists.id = lists_account_assignment.lists_id         left join lists_user_assignment                on lists.id = lists_user_assignment.lists_id  where  lists.tenant_id = 1  group  by lists.id 	0.0118374648462381
21552758	13384	select first joined value, not all	select galery.*, photo.*  from galery left join photo_gallery on galery.id = photo_gallery.id_gallery left join photo on photo_gallery.id_photo = photo.id group by galery.id 	0.000180951185133568
21563030	27353	passing logic of previous column as parameter	select '3' as rowtype     ,dth.enteredby as person     ,coalesce(pdt.[name], app.appname) as project     ,caresult.projecttype     ,dbo.primarytheme(sty.[number], caresult.projecttype) as theme from [sometable] cross apply (select case when (                     kanbanproductid is not null                     and sprintid is null                     ) then 'kanban' when (                     kanbanproductid is null                     and sprintid is not null                     ) then 'sprint' else catagory end         ) as projecttype) as caresult 	0.0816377942778591
21563182	8280	how to get multiple repeted using joins?	select s.studentid, s.dept, v.value from student as s join #temp as v   on v.studentid = s.studentid order by v.studentid 	0.096261719394333
21569081	19121	how to get most recent and second recent values in sql server	select riskid, riskname,        max(case when rnum = 1 then riskdate end) recentdate,        max(case when rnum = 1 then riskscore end) recentscore,        max(case when rnum = 2 then riskdate end) seconddate,        max(case when rnum = 2 then riskscore end) secondscore,        itemid   from (   select *, row_number() over (partition by riskid order by riskdate desc) rnum     from risk    where itemid = 12 ) q  where rnum <= 2  group by itemid, riskid, riskname  order by riskid 	0
21570236	21936	sql replace null values with own text	select    band.name as band_name, 'null' as keyboard_player from    memberof inner join   member on    memberof.mid = member.mid  full join    band on    memberof.bid = band.bid  and    instrument = 'keyboards' where     member.name is null  union select    band.name as band_name, member.name as keyboard_player from    memberof inner join   member on    memberof.mid = member.mid  full join    band on    memberof.bid = band.bid  where   instrument = 'keyboards' 	0.14537408339765
21575499	5806	order mysql results in order for a specific id to be first	select *, abs(product.id - 12) as idorder  from products product {joins}  where category.id = 1, product.active = 1  order by idorder asc limit 0,10; 	0.00117648487551396
21582195	15660	how to test if database is hosted on sql azure?	select case serverproperty('engineedition')          when 1 then 'personal'          when 2 then 'standard'          when 3 then 'enterprise'          when 4 then 'express'          when 5 then 'azure'          else 'unknown'        end 	0.237569409642733
21583877	21903	create list with first and last day of month for given period	select d::date as start_date,(d + '1 month'::interval - '1 day'::interval )::date end_date from generate_series('2014-01-01'::date, '2014-06-30'::date, '1 month'::interval) d 	0
21584672	12937	finding the most recent timestamp per event	select top 1     wn.id, wn.incident_number, wn.created_at, note  from     sn_incident_work_note wn where     wn.incident_number = 'inc0005607474'  and wn.created_at = (select max(iwn.created_at)                     from sn_incident_work_note iwn                     where iwn.incident_number = wn.incident_number) order by id desc 	0
21585001	35943	mysql select from 4 different tables	select p.name as personnamee, h.name as housename, c.name as carname,      e.id as carid, e.name as enginename, e.hp from person p inner join house h on p.house_id = h.id inner join car c on p.id = c.person_id inner join carengine e on c.id = e.id where c.type = 'truck' 	0.00115933123796872
21585214	11953	how can i get up to the last 2 details for each master record?	select s.studentname, t.classname, t.date from students s     inner join trainingdetails t on t.studentid = s.id where t.date in (select top 2 t2.date                   from trainingdetails t2                   where t2.studentid = s.id                   order by t2.date desc) 	0
21593739	40282	how to use 'between' in select statement	select deductions from nhif_tbl where to_end >=$salary and start_from <= $salary; 	0.29962899354946
21595638	32730	group by and having clause in the same query	select  count(p.type) as count,         sum(ifnull(acos(sin((18.5236 *pi()/180)) * sin((p.lat*pi()/180))+cos((18.5236 *pi()/180)) * cos((p.lat *pi()/180)) * cos(((73.8478 - p.lng)*pi()/180))) * 6371.009, 0)) as distance from place as p where p.deleted != 1 group by p.type having sum(ifnull(acos(sin((18.5236 *pi()/180)) * sin((p.lat*pi()/180))+cos((18.5236 *pi()/180)) * cos((p.lat *pi()/180)) * cos(((73.8478 - p.lng)*pi()/180))) * 6371.009, 0)) < 10 	0.221107509989183
21597357	23134	oracle hierarchical query join to selection of all decendants	select connect_by_root(id) as id, id as decendant from table1 connect by prior id = pid order by 1, 2 	0.224243235781142
21618470	37537	calculating median in the same query	select avg(salary) as average,        max(case when seqnum = cnt / 2 then salary end) as median,        max(salary) as maximum,         min(salary) as minimum,        sum(salary) as total,        total as number_of_emp from (select e.*,               count(*) over () as total,              row_number() over (order by salary) as seqnum       from tblemployees e      ) e 	0.00692825875639402
21620182	33040	sql server 2012: return multiple strings within a single column for a common row id	select     playerid, yearid, awards = stuff(         (select ',' + [awardid] from awardsplayers t          where playerid = awardsplayers.playerid                    and yearid = awardsplayers.yearid                         for xml path('')) , 1 , 1 , '') from         awardsplayers group by playerid, yearid 	0
21620405	22444	report - periodic	select origin,destination,loads,average(billable),average(expenses),average(profit)       from table1        where datecol between   @startdate and @enddate       group by origin,destination,loads 	0.376916197435485
21621457	33326	pl/sql select returns more than one line	select getcost(1,100) from dual; 	0.0221301516709417
21626562	9860	postgres rows to columns	select v2.station,    max(day1) as day1,   max(val_day1) as val_day1,   max(day2) as day2,   max(val_day2) as val_day2,   max(day3) as day3,   max(val_day3) as val_day3,   max(day4) as day4,   max(val_day4) as val_day4,   max(greatest(val_day1, val_day2, val_day3, val_day4)) as max_val from ( select v1.*,    (case when v1.day = 1 then v1.valid else null end) as day1,   (case when v1.day = 1 then v1.value else null end) as val_day1,   (case when v1.day = 2 then v1.valid else null end) as day2,   (case when v1.day = 2 then v1.value else null end) as val_day2,   (case when v1.day = 3 then v1.valid else null end) as day3,   (case when v1.day = 3 then v1.value else null end) as val_day3,   (case when v1.day = 4 then v1.valid else null end) as day4,   (case when v1.day = 4 then v1.value else null end) as val_day4 from (select t.valid, t.station, t.value, t.valid - t.issue +1 as day from so_data t) v1   ) v2 group by v2.station order by v2.station 	0.00254164575158684
21630867	19850	show all combinations using mysql query	select t1.product, t2.product, t1.customer,        (case when t1.product = t2.product then sum(t1.qty) else sum(t1.qty + t2.qty) end) from table t1 join      table t2      on t1.customer = t2.customer and         t1.product <= t2.product group by  t1.product, t2.product, t1.customer; 	0.00249831892883507
21634871	31395	comparing 2 columns until the 1st "."	select n.nodeid, n.caption, n.sysname, n.dns, n.ip_address, n.device_type  from nodes n  where left(n.sysname, charindex('.', n.sysname + '.') - 1 )     <> left(n.dns, charindex('.', n.dns + '.') - 1)  order by n.ip_address, n.caption 	0.000653576973246426
21639974	20293	mysql query issue: fetch latest posts	select *  from posts p where postedas = 'user'    and concat(posteddate, postedtime) = (select max(concat(posteddate, postedtime))                                         from posts p2                                         where p.postedasid = p2.postedasid) 	0.00532071532710511
21645971	19472	sum union mysql	select p, sum(conta) as conta  from (   select s.proprietario_id as p, count(*) as conta   from sn_like_spotted s   group by s.proprietario_id     union all   select s.proprietario_id as p, count(*) as conta2   from sn_like_risposta s   group by s.proprietario_id   ) as baseview group by p order by conta desc, p asc 	0.312509946605137
21646444	5775	select records without category in many to many relationship	select i.id from item i where i.id not in ( select r.id_item     from relationship r); 	0.000484285199675613
21649072	23647	oracle arrangements	select count(1) from (select t1.name as name1, t2.name as name2  from locations t1, locations t2 where t1.name <> t2.name) 	0.450055969112385
21657146	6424	short sql challenge with multiple next row on a resultset with group by and having count	select input.* from      (select min(in_id) as idmin, to_id               from input              where us_id=1 group by to_id     ) mintable,      input  where     (input.to_id = mintable.to_id and input.in_id > mintable.idmin)     and us_id <> 1; 	0.040426449134949
21672558	28199	ranking with group by weekly rank	select team,week, (select count(*)+1 from table1 where week=t1.week                                 and points >t1.points ) as rank from table1 t1 	0.204090607820613
21682923	18215	select one primary key using multiple foreign keys from a table	select t1.team_name as team_one,    t2.team_name as team_two,    t3.team_name as winner from schedule s inner join teams t1 on s.team1 = t1.team_key inner join teams t2 on s.team2 = t2.team_key inner join teams t3 on s.winner = t3.team_key 	0
21694756	11599	modifying the query for view	select max(cast(mybool as int)) from myview 	0.731676513593032
21694988	13900	like search on text datatype	select * from `tbltable ` where match(subject) against('abc' in boolean mode) 	0.641718230928863
21695796	21790	mysql query with ranges	select     sum( if(value < 0, 1, 0) ),     sum( if(value between 0 and 10, 1, 0) ),     sum( if(value between 10 and 20, 1, 0) ),     sum( if(value between 20 and 30, 1, 0) ),     sum( if(value > 30, 1, 0) ) from items where id = 43; 	0.123790514054428
21700397	34295	combining multiple rows(which differ by only one field) into single row by making a list from differing column	select ae.userid,        e.firstname,        a.title,        stuff((select ',' + [ai.itemvalue]               from association_items ai               where ai.associationidfk = ae.associationidfk               for xml path('')), 1, 1, '') as itemvalue from associations_employees ae inner join employees e on e.userid = ae.useridfk inner join associations a on a.associationid = ae.associationidfk group by ae.userid, e.firstname, a.title, 	0
21713360	16714	format mysql number to datetime?	select now() - interval 10329 second 	0.00960029343399853
21724490	27004	extract a string from a stored proc definition	select      name,      table_name = case when object_definition(object_id) like '%boctest.s653c36c.liveboc_a.yp040p%' then 'liveboc_a'                       when object_definition(object_id) like '%boctest.s653c36c.liveboc_b.yp040p%' then 'liveboc_b' end from sys.objects o where o.[type] in ('p', 'pc') and name like '%_extract' 	0.0809095010464262
21734467	12188	sql server: join three tables and return with null records	select games.title, genres.name from games left join gamegenres on games.id = gamegenres.gameid left join genres on gamegenres.genreid = genres.id 	0.0265178013669455
21737300	3669	interval 6 month but with user added dates	select  * from    table where   cast(concat(year, '-', month, '-', day) as datetime) >= now() - interval 6 month 	0
21741385	2413	inner join of child table with parent table	select direc from location    inner join runs    on location.rid = runs.id where runs.name = '012114'; 	0.00444171944279454
21752017	12717	mysqli , declare variable and using math to count a median	select x, y,         (select sum(x) - sum(y)         from tablename         where b <= c        ) as z from  tablename 	0.71596851437986
21754909	11816	joining 3 tables mysql	select u.username ,      p.created ,      p.post ,      p.id    ,      p.uid   ,      count(pl.pid) likes from   users u join   posts p on u.id = p.uid left join postlikes pl on pl.pid = p.id group by u.username ,      p.created ,      p.post ,      p.id ,      p.uid 	0.0460577310336674
21761871	22104	sql: only show entry if there is no other entry with special different value in same table	select t1.id_a, t1.status from exampletable as t1 left outer join exampletable as t2     on t1.id_a = t2.id_a and t2.status = 2  where t1.status = 1     and t2.id is null; 	0
21775242	31298	get rows with matching values in column in same table	select group_concat(p.id_product separator '\n') as products  from product p  inner join feature_product fp on (p.id_product = fp.id_product and fp.id_feature = 5)  group by p.id_manufacturer, fp.id_feature_value having count(p.id_manufacturer) > 1 and count(fp.id_feature_value)>1; 	0
21784044	5603	mysql order by data in a different table	select i.id from imagelinks il inner join image i    on il.imageid = i.id where    il.typeid = 1    and il.linkid = 10003    and i.family = 1 order by i.rating desc limit 100 	0.00477650842111728
21785067	40768	sql server: retrieve the group by sum	select axbatchnumber, count(*) as cc from yourtable group by axbatchnumber; 	0.0139497544130858
21792594	27274	how do i aggregate numbers from a string column in sql	select   t.cid   , cast(sum(s.a) as varchar(5)) +        ' out of ' +        cast(sum(s.b) as varchar(5)) as sum   , ((cast(sum(s.a) as decimal))/sum(s.b))*100 as percentage from mytable t   inner join    (select     id     , cast(substring(score,0,2) as int) a     , cast(substring(score,charindex('out of', score)+7,len(score)) as int) b    from mytable    ) s on s.id = t.id group by t.cid 	0.00433887689960005
21792937	5852	mysql joining two queries for sports team	select teams.teamname, res.goals from teams join (     select coalesce(sum(results.gf),0) as goals, results.teamid as teamid from results     group by results.teamid) res on teams.teamid=res.teamid order by goals desc; 	0.147234040360137
21797976	32951	mysql union query output	select     sum( if(bannerid = 3456, clicks, 0) ) as  sales,     sum( if(bannerid = 3457, clicks, 0) ) as  rents from clicksperday where bannerid in (3456, 3457) 	0.728065430577561
21802745	39139	order by select into variable mysql	select max(x_credit) into b_credit from (     select     sum(         (if(notification_type = 'qaccepted',credit*0.5,0)) +          (if(notification_type = 'creditscored',credit,0)) +         (if(notification_type = 'flagpositive',credit,0))     ) as x_credit     from notifications n     left join user_answers ua on ua.question_id = n.question_id and ua.user_id = n.user_id      left join user_credits uc on uc.user_id = n.user_id     where (unix_timestamp() - timestamp) < 7*86400     group by n.user_id ) x 	0.0930926697246567
21820866	3361	time averaging non-continuous data with postgresql9.2	select min(dt."timestamp") as "timestamp_min",          avg(dt."datastream1") as "datastream1_avg_min",          stddev(dt."datastream1") as "datastream1_stdev_min",          count(dt."datastream1") as "datastream1_avg_min"   from "datatable" dt   group by trunc(extract(epoch from dt."timestamp") / (60*10)); 	0.0342416345760783
21821010	31065	sql: how do you return a record in a conditional statement and return a null value if false?	select last_name,         first_name,         birth_date,         city,         state,         employee_id,         work_center_id,         case           when employee_id is not null then work_center_id           else null         end as work_centerid  from   person,         employee  where  city like upper('bethany')         and state = 'connecticut'  order  by employee_id asc; 	0.00251521822514575
21838632	36034	how do i combine select statements for all values in a many-to-many table	select p.id, p.title ,group_concat(k.title separator ' ') `keywords` from  products p left join product_has_keyword phk on(p.id = phk.product_id) left join keywords k on (k.id = phk.keyword_id ) where  phk.id = ? group by p.id 	0.00067969125164559
21838908	40512	select query to get the assistance of employees, in a range of hours	select     distinct(idmtpersonalr),     case (select indicador from mt_reporteradial where idmtpersonalr = m.idmtpersonalr and hora='11')         when 's' then 'x'         when 'n' then '-'     end case as 11_hr,     case (select indicador from mt_reporteradial where idmtpersonalr = m.idmtpersonalr and hora='12')         when 's' then 'x'         when 'n' then '-'     end case as 12_hr,     case (select indicador from mt_reporteradial where idmtpersonalr = m.idmtpersonalr and hora='13')         when 's' then 'x'         when 'n' then '-'     end case as 13_hr,     case (select indicador from mt_reporteradial where idmtpersonalr = m.idmtpersonalr and hora='14')         when 's' then 'x'         when 'n' then '-'     end case as 14_hr,     case (select indicador from mt_reporteradial where idmtpersonalr = m.idmtpersonalr and hora='15')         when 's' then 'x'         when 'n' then '-'     end case as 15_hr from     mt_reporteradial m where     fecha = '2014-02-10' 	0
21840107	29556	sql query next lowest value	select x.*,        y.odometer as prev_odom,        y.gallons as prev_gallons,        (x.odometer - y.odometer) / x.gallons as mpg   from tbl x, tbl y  where y.odometer =        (select max(z.odometer) from tbl z where z.odometer < x.odometer) union select x.*, null, null, null from tbl x where id = 1 order by 1 	0.00183205668654347
21840876	11613	concatenate two or more different tables in mysql	select     tablea.id, tablea.price, tablea.catalogue,      if(tableb.id is null, 0, 1) as b,     if(tablec.id is null, 0, 1) as c from tablea left join tableb on tablea.id = tableb.id     left join tablec on tablea.id = tablec.id 	0.000687078968379207
21849203	18570	sql view with count and group by	select      a.city,     count(*) as properties,     avg(l.askingprice) as askingprice  from address a inner join property p on p.addressid = a.addressid inner join listing l on p.propertyid = l.propertyid where l.askingprice is not null and l.saledate is null group by a.city 	0.429784235863832
21861566	12463	how to find most recent date given a set a values that fulfill condition *solved, please see my response below*	select * from (table) t  where t.date in  (select max(date) from table sub_t where t.id = sub_t.id and (date !> (currentdate)) and preference in (select preference from (hierarchy_table) where hierarchy ='vegetables') and id in ('124') 	0.000287691925060419
21862709	35407	mysql, check if result has value, if not take another	select a.type, a.page_id from   table a          inner join        (select    type, max(user_id) as user_id         from      table         group by  type ) b        on a.type = b.type and a.user_id = b.user_id 	0.000134356954067545
21864133	24439	using order by and getting most recent version of records	select id, "date", col_a from (select v.*,              max("date") over (partition by substr(col_a, 1, 1),                                             substr(col_a, 8)                               ) as maxdate       from versiones v      ) v where "date" = maxdate; 	5.76035551391092e-05
21867238	27370	query sql with two table in one and show the counting the total number	select movie.celeb, moviecount, albumcount  from    (select celeb, count(1) moviecount     from star group by celeb) movie inner join   (select celeb, count(1) albumcount     from releases group by celeb) album on movie.celeb=album.celeb 	0
21875721	18337	database sql queries, compare values	select cid,         count(cid),         ( count(cid) = (select count(apc)                         from   airport) ) as result  from  (select cid,                deptapc         from   customer                natural join ticket                natural join flightticket               natural join flight         union         select cid,                arrapc         from   customer                natural join ticket                natural join flightticket                natural join flight)  group  by cid; 	0.0123717502816493
21893824	6962	sql query to count multiple defined columns within one query	select *, ( select  sum(date_end > 1392569012 && date_start <= 1392569012) from tbl_events as event  left join tbl_event_events as ee on event.event_id = ee.event_id where event.event_type = 5 && event.user_id = '".$user->getuserid()."' order by expired,pending,active), (date_end < 1392569012) as expired,  (date_start > 1392569012) as pending,  (date_end > 1392569012 && date_start <= 1392569012) as active  from tbl_events as event  left join tbl_event_events as ee on event.event_id = ee.event_id where event.event_type = 5 && event.user_id = '".$user->getuserid()."' order by expired,pending,active 	0.00785914099825852
21898265	34395	group by week day and month	select  sum(x)  from    demo_table  where   datename(weekday,date)='sunday' group by datepart(month,date) 	0
21910050	9154	mysql & php select from 2 different tables + make a array of it	select t1.* from organisation t1 left join bought t2 on t2.organisation_id = t1.organisation_id where t2.organisation_id is null 	0.000169947341685833
21916400	22211	sql server - how to filter rows based on matching rows?	select   accountid  ,min(sdistatus) as minsdistatus into #mintable from #temptbrb group by accountid select * from #temptbrb t join #mintable m on      t.accountid = m.accountid      and t.sdistatus = m.minsdistatus drop table #mintable 	0
21923602	7670	combining 2 sql queries from a single table and being able to update it	select *   from tbltest  where ((f1 >= f1upper and f1 <= f1lower) and        (f2 >= f2upper and f2 <= f2lower)..         . and (f8 >= f8upper and f8 <= f8lower))     or (f4 like '~prio' and (f8 = currentuser or f8 = location))  order by order1, order2,  order 3 .. .  order 8 	0.00241356158773956
21925712	11776	joining two separate queries in a postgresql ...query... (possible or not possible)	select distinct on (post_id) * from instances i where i.user_id <> 3 and i.helped_by_user_id is null and not exists (   select 1   from instances ii   where ii.post_id = i.post_id   and ii.helped_by_user_id = 3 ) order by i.post_id limit 10; 	0.345646222021792
21926557	39953	sql statement to output record of person that has more than x counts of a condition	select      distinct name from      attractionvisit      natural join      ticket      natural join      visitor natural      join attraction  where      attractionname = 'super rollercoaster' group by      visitid, day    having      count(*) > 50; 	0
21936329	39913	change value from 1 to y in mysql select statement	select if(inty = 1, 'yes', 'no') as internetapproved from table1 	0.00151612437229469
21936926	20935	how to query for one - many relation	select  tablea.id, tablea.name, tableb.email  from tablea left outer join tableb on tableb.a_id = tablea.id group by tableb.a_id; 	0.0402516855133523
21941718	32508	get sum of column values from sql query	select     sum(c.column2) from table1 c      left join table2 d on d.column_id = c.column_id group by c.column1 	0.000115982196604682
21945042	21258	turning multiple columns/rows into a single column/multiple rows	select columnx as id from tablea union select columny as id from tablea union select columnz as id from tablea 	0.000483852596181951
21950860	15280	mysql query - get row value based on column name in a different table	select info.* from info join inventory on (itemid = 'item1' and item1 > 0)                or (itemid = 'item2' and item2 > 0)                or (itemid = 'item3' and item3 > 0) where info.itemclass = 'class1' and inventory.userid = $a 	0
21971617	22309	how can i fetch data from more than two tables?	select count(student.name) from student  inner join marks     on marks.fields_id = student.fields_id where marks.marks>( select avg(marks)                     from marks ); 	7.7786668303808e-05
21972260	26403	group by a substring in field	select split(timestamp," ")[3] as yr, split(timestamp," ")[2] as mon, count(timestamp) from dataset group by split(timestamp," ")[3], split(timestamp," ")[2]; 	0.0896737370880745
21976665	12745	php mysql highscore table	select *   from game_log gl  inner join users u     on gl.user_id = u.id  inner join county c     on u.countyid = c.countyid  where not exists (select 1           from game_log gl2          where gl2.user_id = gl.user_id            and gl2.score > gl.score)    and not exists (select 1           from game_log gl2          where gl2.user_id = gl.user_id            and gl2.time < gl.time            and gl2.score = gl.score)  order by gl.score desc, gl.time limit 20; 	0.162706359092085
21977374	13492	sql - sum of some rows, minus sum of other rows	select customer_code,        sum(case              when trans_type = 'drinv' then               trans_value              else               -trans_value            end) as net_sales   from dr_trans  group by customer_code 	0
21986941	34865	select into query adding a second count column with different clause	select id_matched      , count(*) s_count      , sum(case when unique = 1 then 1 else 0 end) count_unique   into steven_1c    from batch   where match = 200   group by         id_matched 	0.00065978863105424
21991587	4762	sql query to return more than one copy of same row, if hit on more than one where clause	select c1,c2,c3 from [mytablename] where c1=x  union all  select c1,c2,c3 from [mytablename] where c3=z 	0
22002540	10085	access sum of nested countifs	select t.*,        iif(numgt10 >= 3 then 6, iif(numgt10 >= 2, 3, 0)) as calculatedfield from (select t.*,              (iif(ppts >= 10, 1, 0) +               iif(ast >= 10, 1, 0) +               iif(reb >= 10, 1, 0) +               iif(blk >= 10, 1, 0) +               iif(stl>= 10, 1, 0)              ) as numgt10                    from t      ) t; 	0.521378628850084
22014216	17906	mysql get % of dates from timestamp column for google linechart	select count(date(`joineddate`)) as `no_of_members_on_this_day`,                                          date(`joineddate`) as `date_of_signup`                              from   tablename                              join (                                     select 100 / count(*) as factor                                     from tablename                                   ) as t                             group by                                  date(`joineddate`) 	0
22020520	11354	mysql sum per ids without subqueries	select id,            otherid,           sum(value1*value2) as sum     from your_table group by id, otherid; 	0.00221229004977125
22033019	30111	sql statement join three tables	select di_id,         di_name,         di_location,         ig_name,         in_latitude,         in_longitude  from   dam_info         left join instrument_group                on ig_diid = di_id         left join instruments                on in_igid = ig_id  group  by di_id; 	0.534052939736551
22035479	39293	display alphabetical order a list of name and surname	select t1.id        as user_id,         t2.field_val as surname,         t3.field_val as name  from   $table_name t1         join $table_name2 as t2           on ( t2.sub_id = t1.id                and t2.field_name = 'nom :' )         join $table_name2 as t3           on ( t3.sub_id = t1.id                and t3.field_name = 'prénom :' )  order  by t2.field_val 	0.000771342993498008
22039322	16958	fetching table data with single query	select @pv:=cid as 'cid', name, parentid from categories join (select @pv:=0) tmp where parentid = @pv 	0.0173214382366897
22044767	33873	sql return x rows depending on the value within same row	select your_table.customer      , your_table.noofconnections      , numbers.number as connectionnumber from   your_table  inner   join dbo.numbers     on numbers.number between 1 and your_table.noofconnections 	0
22049699	14799	phpmyadmin search returns row but sql returns null	select * from  `tbltable` where  `field` like  '%something@something.com%' 	0.529312413631668
22053015	37755	sql server select in join	select i.code, sum(qty_sold) sales, i.qty_available, i.location from inventory i     join invoice_history ih on i.code = ih.itemcode group by i.code, i.qty_available, i.location 	0.645589809008485
22054517	15774	how to get corresponding value from query data	select marks.from, marks.given, names.fistname   from marks   join names     on marks.given = names.username  where marks.from = 'raj' 	0
22055285	33783	sql specify query to multiply by latest value on subquery	select sum(a.costoimp*movstocktotal.stock) from     vsboremix.dbo.compralinea as a  inner join     (select compralinea.idarticulo, max(compralinea.iddocumento) as iddocumento, idlistaempresa     from     vsboremix.dbo.compralinea join vsboremix.dbo.documento on compralinea.iddocumento = documento.iddocumento join vsboremix.dbo.articulo on compralinea.idarticulo=articulo.idarticulo     where iddeposito in(30,38,40,44,50,60,70,90,100) and compralinea.costoimp>0.0 and idseccion=101     group by compralinea.idarticulo, idlistaempresa) as b on b.idarticulo = a.idarticulo and b.iddocumento = a.iddocumento  join vsboremix.dbo.movstocktotal on a.idarticulo = movstocktotal.idarticulo and b.idlistaempresa=movstocktotal.idempresa 	0.00381249196719155
22059653	12750	query wsus database for required updates per server	select left(tbcomputertarget.fulldomainname,30) as [machine name]            ,count(tbcomputertarget.fulldomainname) as [# of missing patches]            ,tbcomputertarget.lastsynctime as [last sync time] from tbupdatestatuspercomputer inner join tbcomputertarget on tbupdatestatuspercomputer.targetid =                       tbcomputertarget.targetid where (not (tbupdatestatuspercomputer.summarizationstate in (’1′, ’4′))) and             tbupdatestatuspercomputer.localupdateid in (select localupdateid from dbo.tbupdate where updateid in                     (select updateid from public_views.vupdateapproval where action=’install’)) group by tbcomputertarget.fulldomainname, tbcomputertarget.lastsynctime order by count(*) desc 	0.197764832897511
22069742	2721	how to get a row from a table with no ids	select a.id, b.a, b.b, b.c   from a   join b     on(a.a=b.a)     and(a.b=b.b)     and(a.c=b.c) 	0
22073807	4214	select most recent rows from one table 1 and join to get rows from table 2	select fname, city, my_date from (select t1.fname, t2.city, t2.my_date       from t2, t1       where t2.id = t1.id       order by t2.my_date desc) where rownum <= 2; 	0
22087991	34073	sql rounding mechanism	select round(82.01*2,1)/2 as [round amount] 82.00 select round(82.02*2,1)/2 as [round amount] 82.00 select round(82.03*2,1)/2 as [round amount] 82.05 select round(82.04*2,1)/2 as [round amount] 82.05 select round(82.05*2,1)/2 as [round amount] 82.05 select round(82.06*2,1)/2 as [round amount] 82.05 select round(82.07*2,1)/2 as [round amount] 82.05 select round(82.08*2,1)/2 as [round amount] 82.10 select round(82.09*2,1)/2 as [round amount] 82.10 	0.520190043194523
22094738	22874	how distinct and different results of the same field, differentiating rows	select a.id_field, b.id_field from sometable a inner join sometable b on a.id_field < b.id_field 	0
22108214	23397	sql grabbing all records for x column that equal a, if any of those records include b in the y column	select a.* from yourtable a join (select distinct [object]       from yourtable       where [group] = 'home'       )b on a.[object] = b.[object] 	0
22112477	16764	sql select rows from two different tables with different column names	select * from ( select id as amount, ... from t1 union all  select id as amount, ... from t2 ) t order by date 	0
22121420	32024	columns in sql query are not grouped	select       dept.name as deptname, count (t.id) as totalservicenumber,     sum(case when ss.status <> 'resolved' then 1 else 0 end) as unresolvednumber,     sum(case when t.fixtime <= '120' then 1 else 0 end) as resolvedlessthantwohoursnumber,     sum(case when t.fixtime > '120' then 1 else 0 end) as resolvedmorethantwohoursnumber, from     dbo.tickets as t,     dbo.servicestatuses as ss,     dbo.computerdesks as desk,     dbo.personnels as person,     dbo.departments as dept where     ss.id = t.servicestatusid     and t.computerdeskid = desk.id     and desk.personnelid = person.id     and person.departmentid = dept.id group by     dept.name 	0.0172629567773498
22123019	23465	mysql - select row by user_id based on column value of other rows with the same user_id	select * from table t where t.status = 'inactive'      and not exists(select 1 from table t2                      where t2.user_id = t.user_id                      and t2.status <> 'inactive') 	0
22123770	15692	mysql - trying to combine 3 selects into one	select profile_gender as gender, count(*) as users,        sum(profile_createdate > date_sub(curdate(), interval 1 day) as cnt_1day,        sum(profile_createdate > date_sub(curdate(), interval 7 day) as cnt_7day from login group by profile_gender; 	0.0032912977145521
22129708	41315	select mutiple rows with max date	select * from evaluari where magazin = 186 and date = (select max(date) from evaluari where magazin = 186) 	0.00307763453402422
22142446	5846	calculating mode for time column	select range as rangestart, range+1 as rangeend from (    select strftime('%h',starttime) as range, count(*) as cnt from events    group by strftime('%h',starttime) ) order by cnt desc  limit 1; 	0.0423322417126789
22156009	24623	php/sql: select 2 columns 3 times with different values	select id  from ads  where (onoff = '1' and again = '0')    or (onoff = '2' and again = '1')    or (onoff = '3' and again = '1') 	0
22166454	27892	i need to set the start date and end date into a variable in stored procedure	select @startdate = dateadd(m, datediff(m, 0, current_timestamp), 0) startdate,        @enddate   = dateadd(m, datediff(m, 0, current_timestamp) + 1, -1) enddate 	0.00137460777173221
22166831	5165	intersection of two mysql queries	select sum(duration), week, type, year  from up26rotordowntime  where year = 2005 and week >= 10    or year between 2006 and 2013    or year = 2014 and week <= 14 group by year,week 	0.0291516203208892
22194300	18047	mysql select random users but more chances for those with lower votes	select * from ints; + | i | + | 0 | | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | + select i      , rand()/(i+1) wght    from ints   order      by wght desc; + | i | wght                  | + | 1 |    0.4722126251759125 | | 0 |    0.3937836097495478 | | 3 |     0.217650386474701 | | 2 |   0.18025848441470893 | | 4 |   0.14613628009905694 | | 7 |   0.11937898478412906 | | 8 |   0.08080622240562157 | | 9 |   0.07711844041675184 | | 5 |  0.006933732585609331 | | 6 | 0.0022811152594387277 | + 	0.00356702289080611
22208984	38416	filtering sql query	select  distinct     room.roomid,      room.roomnumber,      room.phoneextension,      room.specialnotes ,     roomtype.description from            room      inner join  roomtype    on room.typeid = roomtype.typeid where   room.deleteflag=0 and room.roomid not in (select roomid from reservation where     (reservation.resstatus <> 'occupied' or reservation.resstatus = null)     and (reservation.resstatus <> 'reserved' or reservation.resstatus = null)     and (reservation.resstatus <> 'confirmed' or reservation.resstatus = null)) order by    roomnumber 	0.575518839599943
22216902	25865	trying to select all fields in a row with the lowest min( )	select min( price ) as mprice, `unique_url`  from `product_price`  where `barcode` = '" . $product_barcode . "' and `active` = '1' group by `user_id`  order by mprice asc  limit 1 	0.000143822142494545
22224401	14273	how to select the latest record based on version number?	select bd.* from t1 bd where bd.version in ( select max(bd1.version) from t1 bd1 where bd1.number = bd.number group by bd1.number) 	0
22224987	17530	getting average number of uploads (or something else) per day	select avg(anz) from (     select     date(from_unixtime(your_ts_column)) as my_date,     count(*) as anz     from     your_table     group by my_date ) subquery_alias 	0
22230473	26580	sysdate minus 2 different days	select     version_name as version,     min(reconcile_start_dt) as dates from    sde.gdbm_reconcile_history where     reconcile_result = 'conflicts' and     reconcile_start_dt > sysdate -         case to_char(sysdate, 'd')             when '2' then 2             else 1 end group by version_name order by 2 asc nulls last 	0.000257798451890754
22238229	40217	mysql query for counts from multiple tables	select j1.model as jeep1model,        count(distinct j1.vin) as jeep1counts,        j2.model as jeep2model,        count(distinct j2.vin) as jeep2counts,        j3.model as jeep3model,        count(distinct j3.vin) as jeep3counts,        count(distinct j1.vin)+        count(distinct j2.vin)+        count(distinct j3.vin) as total from (select distinct model from jeepmart1 union select distinct model from jeepmart2 union select distinct model from jeepmart3)a left join jeepmart1 j1 on j1.model = a.model left join jeepmart2 j2 on j2.model = a.model left join jeepmart3 j3 on j3.model = a.model group by a.model 	0.0118735416144253
22238403	4172	mysql selecting table that has the most columns?	select table_name, count(*) as c from information_schema.columns group by table_name order by c desc limit 1; 	0
22239247	28827	sql self-join on the same line	select  e1.emp_num "employee id", e1.emp_lname "employee first name",  e1.emp_fname "employee last name",  e1.emp_manager "managers id for employee",  e2.emp_lname as manageremp_lname,  e2.emp_fname as manageremp_fname  from carrm.employee e1  left outer join carrm.employee e2 on e1.emp_manager = e2.emp_num; 	0.00448723103648364
22241279	8181	to retrieve data whose third character is '_' underscore?	select name from t1 where substring(name, 3 , 1) = '_' 	0.00333375732683727
22244992	26015	return list values with function	select name, times,   (select max(times) from info i2 where i2.times<i1.times and i1.name=i2.name and i2.card_nr=@card_nr )   from info i1  where  card_nr=@card_nr 	0.0414899304996527
22247442	1777	pulling all information on a user from multiple tables	select a.* from vehicle_master a  join gcm_users b on a.registration_no = b.registration_no where user_id =  1 	0
22250115	5497	mysql ordering by value from two columns	select * from my_table order by ifnull(discount_price, product_price); 	0.000233709715647191
22254846	27613	sum rows of data	select t.check_number, sum(t.amount) from chkdetail_t as d join cheheader_t as h   on h.check_acct = t.check_acct group by t.check_number 	0.00215577908530679
22280477	19176	select greatest duplicate and unique row	select * from newsfeed where id in (select max(id) from (select id, case when update = 0 then id else update end update1 from newsfeed)t1 group by update1); 	0.000226149244533636
22299985	27644	sql query help 1 to n	select  e.id,          e.name,         case when ue.entryid is null then 0 else 1 end as userflag from    entry as e         left join user_entry as ue             on ue.entryid = e.id             and ue.userid = x 	0.43151486746548
22342253	10339	fetch the employee having no address?	select * from emp where id not in(select distinct(id) from address); 	0.00126338927721807
22346727	1381	sql query to return amount of sales and amount of salespersons	select date_format(invoice_date, "%y-%m") as date,  count(*) as items, count(distinct id_user) as salespersons from report  group by date 	0
22350213	28801	get sum for each group in group by query	select      data.*,     d2.country_sum,     d3.year_sum from      (select year, country , product,sum(profit)       from table t1      group by year, country , product) data        join         (select year, country,sum(profit) as country_sum          from table t1          group by year, country ) d2 on data.year=d2.year and data.country=d2.country       join         (select year, sum(profit) as year_sum          from table t1          group by year) d3 on data.year=d2.year 	0.000559055360715967
22353426	19748	unicode strings: difference between habo and håbo	select *    from g2_se_raw_zip   where province collate utf8_swedish_ci equals 'håbo' select *    from g2_se_raw_zip   where province collate utf8_swedish_ci = 'håbo' 	0.0717382628311621
22361733	34552	how to rank and display side by side	select t1.rank, t1.cono, t1.value 'a-value', t2.rank, t2.cono, t2.value 'b-value'  from  (select *,row_number() over (order by value desc) rank from temp1 where type=1) t1  join   (select *,row_number() over (order by value desc) rank from temp1 where type=2) t2  on t1.rank=t2.rank 	0.0115773321800589
22362173	4300	how can i write a better stored procedure to return all records with a flag/bit field = 1 in which i pass the flag-field's name into the sproc?	select   [name] from   [dbo].[peeps] where    ([eligible] = case when @flagname = 'eligible' then 1 else [eligible] end) and   ([lefty] = case when @flagname = 'lefty' then 1 else [lefty] end) and   ([contractor] = case when @flagname = 'contractor' then 1 else [contractor] end); 	4.70545566911712e-05
22383475	24298	order by date from two tables using union alternative	select if(comment = 'view', 'view', 'comment') as type, comment, fullname, created_at from (   select comment, fullname, comments.created_at   from comments   where comments.photo_id = 14   union   select 'view', user, views.created_at   from views   where views.pid = 14 ) tbl order by created_at desc 	0.0157056838288135
22384250	28654	how to calculate time remaining - based on estimated time x rows avaiable	select count (units) as orders_remaining, count(units) * 1.5 as minutes_remaining from orders where units between '0001' and '2500' 	0
22393789	10078	mysql - convert date string to real date when we have timezone in the string	select str_to_date( concat( substr( 'thu nov 07 15:05:22 est 2013', 1, 20 ) , substr( 'thu nov 07 15:05:22 est 2013', 25, 4 ) ) , '%w %b %d %h:%i:%s %y' ); 	0.00767796686684166
22401896	32651	want to group all the ids, but getting error	select title,sales_price,identifiers from books inner join book_sales on books.book_id = book_sales.book_id group by title,sales_price,identifiers 	0.00320210273480357
22407016	18178	mysql: find start and end timestamp of a consecutive count	select count(*), min(time_stamp) as starttime, max(time_stamp) as endtime from (   select if(@prev <> marker, @s:=@s+1, @s:=@s) as `index`,      time_stamp, @prev:=marker marker   from     tbl, (select @s:= 0, @prev:= -1) s ) tmp where marker = 1 group by `index` 	0
22409468	28352	mysql select rows that do and do not	select distinct(person_id)  from invoices where    person_id in      ( select person_id from invoices where issue_date like '2013-07-%' or issue_date like '2013-09-%' )   and person_id not in     (select person_id from invoices where issue_date like '2013-08-%') 	0.0309120695516664
22435248	31431	how to compare a string to date in mysql?	select *  from table1 t1, table2 t2 where str_to_date(t2.tran_date, '%m/%d/%y') = t1.tran_date 	0.00201734929903491
22441969	15063	dynamic field name selection in mysql query	select case day(now()) when 1 then day1 when 2 then day2 else day29 end as thisday from mytable 	0.240097919956189
22448473	27166	how to fetch records from other table using inner join	select t1.*,t2.* from (select uid as userid, count(uid) as artisttotalviews  from artist_view group by uid order by artisttotalviews desc)t1 inner join table2 t2 on t1.userid = t2.id; 	0.000157529604196525
22454545	21007	convert columns of data to rows of data in sql server	select * from  (select header, data from csvtest_match) as t pivot (min(data) for header in ([home team], [away team], [kick off time],                  [kick off date], [home goals], [away goals])) as t2 	6.71782738141377e-05
22480323	2336	select limited set of fields from inner query with preserved order	select * from (     select distinct on (s0_.id)         s0_.id,         s0_.created_at,         s5_.sort_order     from          surveys_submits s0_         inner join surveys_answers s3_ on s0_.id = s3_.submit_id         inner join surveys_questions s4_ on s3_.question_id = s4_.id          inner join surveys_questions_references s5_ on s4_.id = s5_.question_id      order by         s0_.id,         s0_.created_at desc,          s5_.sort_order asc ) s order by     created_at desc,     sort_order asc limit 25 	0.130814096359556
22485275	27712	sql outer join 3 tables merging data	select tblcustomer.customerid, tblevents.eventid, null as tblpending.pendingid from dbo.tblcustomer left outer join dbo.tblevents on dbo.tblevents.customerid = dbo.tblcustomer.customerid  union select tblcustomer.customerid, null as tblevents.eventid, tblpending.pendingid from dbo.tblcustomer left outer join dbo.tblpending on dbo.tblcustomer.customerid = dbo.tblpending.customerid 	0.187601434738702
22509095	35757	how to join 2 tables into one query using fields in third table?	select users.id as [userid], segments.value as [segment], report_1.total, report_2.total from users, segments left outer join report_1 on      report_1.userid = users.id and report_1.segment = segments.value left outer join report_2 on      report_2.userid = users.id and report_2.segment = segments.value 	0.000110844755905294
22510619	25382	how to replace numeric character with "%" in mysql?	select     replace(         replace(             replace(                 replace(                     replace(                         replace(                             replace(                                 replace(                                     replace(                                         replace(videotitle, '0', '%'),                                         '1', '%'),                                     '2', '%'),                                 '3', '%'),                             '4', '%'),                         '5', '%'),                     '6', '%'),                 '7', '%'),             '8', '%'),         '9', '%') as titlemasked 	0.411371808646267
22511019	21409	select rows where col1 is value and another row where col1 is not value	select count(distinct callid) as r  from voipnow.ast_queue_log  where queuename = '0536*401'  and time > '2014-03-19 15:38:00'  and callid not in (select callid from voipnow.ast_queue_log                     where event in ('connect', 'abandon', 'ringnoanswer')) 	0.000153699550423713
22521812	20027	how to query rows with one matching and one non-matching field	select distinct mk.* from tblmodkeys mk join tblallkeys ak1 on mk.fldcode = ak1.fldcode  left join tblallkeys ak2 on mk.fldkey = ak2.fldkey where ak2.fldkey is null  	0
22525691	28483	subtract two dates in oracle	select trunc(currentdate )-trunc(previousdate) from temptable; 	0.0026187995053955
22530434	26956	generate scripts for specific data using query	select *  into databasea.dbo.tablea_copy from databasea.dbo.tablea where model = 'animal_b' 	0.0759060905871922
22553782	35367	convert minutes in hours	select convert(varchar(5), dateadd(minute,122, 0), 108) 	0.00120734185653904
22576635	21617	how to get the current year to current date in sql server 2008	select  * from    yourtable where   year(yourcolumn) = year(getdate())         and datepart(dy, yourcolumn) <= datepart(dy, getdate()) 	0
22600672	5301	mysql two left joins distinguish same column	select u.ig_user_id as ig_user_id, u2.ig_user_id as followed_user_id from follow_reconciliations f left join users u on (u.user_id = f.user_id) left join users u2 on (f.followed_user_id = u2.user_id) 	0.0661975634826091
22606253	22176	mysql query different random conditions	select question from  ( (select question from question where questiontype = 'identification' order by rand() limit 10) union all (select question from question where questiontype = 'multiple choice' order by rand() limit 20) ) t order by rand() 	0.0413977455307845
22627712	39493	combining multiple columns into one- sql server 2008	select case when isprod=1 then 'isprod'             when iscompetprod=1 then 'iscompetprod'             when isother=1  then 'isother'         end [new] from table1 	0.00289812222040684
22633261	38504	how to calculate sum of the years into a new column for current to previouse years	select cs.*,        sum(cs.activeeachyear) over (order by cs.[year]) as totalactiveinsystem from currentscenario cs order by cs.[year] desc; 	0
22640864	14057	php/mysql - calculate total for each reservation	select datediff(a.chkout,a.chkin) * a.guests as meals from table as a  where a.chkin > '0000-00-00' and a.chkout < '0000-00-00 	0
22669951	26576	querying postgresql table statistics	select table_name, operation_type, count(*) from db_stats.db_stats_table_call group by table_name, operation_type order by table_name, operation_type 	0.0630206666923465
22672498	27424	finding data from table a and table b relation	select * from tablea where status = 'inactive' and not exists (select * from tableb where tablea.aid = tableb.aid) 	0
22699571	23198	sql one id join two names	select c1.color as color1, c2.color as color2 from car car inner join color c1 on c1.id = car.color1 inner join color c2 on c2.id = car.color2 	0.000321044264687945
22708949	32652	running total sql server - again	select a.expecteddate, a.expectedamount, (select sum(b.expectedamount)                        from unpaidmanagement..expected b                        where cast(b.expecteddate as int) <= cast(a.expecteddate as int)) from   unpaidmanagement..expected a 	0.168338524327473
22716578	28624	mysql join: get parts with count for each type	select  pa.part_id, pa.part_name, coalesce(sum(case when po.type = 1 then 1 else 0 end), 0) as count_posts_type1, coalesce(sum(case when po.type = 2 then 1 else 0 end), 0) as count_posts_type2, coalesce(sum(case when po.type = 3 then 1 else 0 end), 0) as count_posts_type3 from parts pa left join posts po on po.part_id = pa.part_id group by pa.part_id, pa.part_name 	0.000392883270734782
22721032	12506	find distinct value from comma seprated single string	select group_concat(distinct trim(substring_index(substring_index(value, '|', n.n), '|', -1)) separator ',' ) as `values`   from table1 t    cross join (select 1 as n union all select 2 ) n   order by `values` 	0
22723028	17727	mysql merge different id's into one column	select cityid as id from tablea union select villageid as id from tableb 	0
22725173	34123	mysql union all with left join	select     comments.*, users.company, users.contact_person, users.email     from         comments     left join users on users.user_id = comments.user_id     where         comment_id = %s union all select activity.*, users.company, users.contact_person, users.email     from         activity     left join users on users.user_id = activity.user_id     where         comment_id = %s order by     timestamp asc 	0.643962956324898
22735718	9455	searching query in orders to selecting entries which have not any related entry	select distinct forecastid   from odd  where forecastid not in        (select forecastid from odd join bet on bet.oddid = odd.oddid) 	0
22745317	8698	get the count of field and group concat	select t.category, group_concat(concat(t.subcategory,',',t.cnt) separator '|') `concat` from ( select     `category`.`heading` as `category`     , `subcategory`.`heading` as `subcategory`     , count(`shop`.`subcat_id`) as cnt from     `shop`     inner join `subcategory`          on (`shop`.`subcat_id` = `subcategory`.`subcat_id`)     inner join `category`          on (`shop`.`cat_id` = `category`.`cat_id`) group by `shop`.`subcat_id` ) t group by t.category 	0.00107200513882116
22747343	34030	inner join on same table with avg	select a.page_id, a.num_ses, avg(c.num_pg_ld_sespg) as avg_ses_pg_exist   from (select page_id, count(distinct session_id) as num_ses           from tbl         where event = 'page load'          group by page_id) a   join (select session_id, count(*) as num_pg_ld_ses           from tbl           where event = 'page load'          group by session_id) b   join (select session_id, page_id, count(*) as num_pg_ld_sespg           from tbl         where event = 'page load'          group by session_id, page_id) c     on a.page_id = c.page_id    and b.session_id = c.session_id  group by a.page_id, a.num_ses  order by a.page_id 	0.16408859188673
22759561	40220	display data not present in another table	select id,code from boxes where id not in(select temple_id from boxes_to_pages) 	0.000129682691219453
22764363	12348	sql server 1 to many - groupby query	select distinct catid, 0 as header, catname from categories union select distinct catid, 1, subcategoryname from subcategory order by catid, header, catname 	0.624317163772395
22767352	38736	sql resulting table satisfies two conditions	select name from owner where type in (select distinct type from owner where name = 'tim') group by name having count(distinct type) = (select count(distinct type) from owner where name = 'tim') 	0.00829188995866003
22768714	2249	how to exclude records in select query for tablea where tablea.user_id does not exist in user.id	select  count(*) from    private_messages pm where   pm.recipient_id = '" . $user_id . "'         and pm.id not in (             select  message_id             from    pm_views         )         and pm.sender_id in (             select  id             from    users         ) 	0.159956973629565
22782870	8324	sql query: join	select p.idsentence, p.idpath, p.token, p.istv, r.rel, t.tag from path p  left join relation r on p.id = r.id join content t on p.idc = t.idc join  ( select idpath,            max(istv = 'true') as hastv,           count(*) as pathlength    from path     group by idpath   ) pf on p.idpath = pf.idpath     and pf.hastv = 1    and pathlength between 2 and 3 join  ( select idsentence, count(distinct(idpath)) as paths    from path    group by idsentence  ) ps on p.idsentence = ps.idsentence    and ps.paths between 2 and 3 	0.771641521025625
22795588	12816	mysql - query from two tables	select distinct table2.* from table2 left join table1 using (id) where status='public' or user_id='someuser'; 	0.008347274535799
22795948	23331	simple query on mysql sakila database	select      f.films,     a.first_name,     a.last_name from films f join film_actor fa on fa.film_id = f.id  join actor a on a.id = fa.actor_id where a.last_name like"%sandra%" or a.first_name like"%sandra%"  	0.797908204347219
22804363	10714	how do i select the population of a user table as an increasing value by date?	select t.date ,  @population := @population+t.per_time population from ( select  date_format(`last_login` ,'%y-%m') `date`, count(*) per_time from  table1   where created > '2012-07-01 00:00:00' group by `date` ) t , (select @population:=0) p 	0.00125395232695084
22805856	37804	how to split first 4 rows and sum the remaining records and show as last record	select col1,col2,col3 from dbo.t3 where col1<='i4' union select '>i4',sum(col2),sum(col3) from dbo.t3 where col1>'i4' 	0
22809512	15482	mysql comma seperated values and using in to select data	select * from destinations where find_in_set('us',destinations); 	0.000648140810743224
22816985	3293	ignore null (empty) value mysql select avg	select avg(question1) from ... where question1 is not null; 	0.0589930619079069
22818016	39009	find duplicate values in 2 columns in mysql	select f_id, status, count(id) from catalog_sizes group by f_id having strcmp(min(status), max(status)) = 0 	0
22830670	23005	get function parameter from select query	select * from information_schema.parameters where specific_name = 'your function name' 	0.10950554918229
22838181	8794	how to count for a specific value column wise?	select  sum(cola) as cola,  sum(colb) as colb,  sum(colc) as colc,  sum(cold) as cold  from table1 	0.000128119780703907
22841635	33637	sql server displaying data when its available	select sitename       ,sum(case when  datepart(dd,orderdate) > datepart(dd,dateadd(day, 1-datepart(weekday, getdate()), getdate()))                 then 1                 else 0             end) as orders   from siteorder   where sitename in ('site1','site2','site3','site4','site5','site6','site7')  group by sitename having sum(case when datepart(dd,orderdate) <= datepart(dd,dateadd(day, -6 -datepart(weekday, getdate()), getdate()))                 then 1                 else 0             end) > 1  order by sitename 	0.0132186771778416
22845110	2757	sql find bad combination	select   item_id,   dep_id from   table group by   item_id,   dep_id having   count(distinct value_id)>1 	0.23121186707942
22857108	23412	select inner join only returns one result	select p.code, p.name, sum(h.pb = 1),  sum(h.pg = 1), sum(h.pa = 1), sum(h.goedkeuringdoornew = 'gf'),  sum(h.goedkeuringdoornew = 'sb'), sum(h.goedkeuringdoornew = 'via'), sum(h.blanco) from psthostess p inner join `psttodo-uit` h on h.`hostess code` = p.code where p.indienst = 1 group by p.code, p.name 	0.0575582875792297
22858459	1113	checking for duplicate rows on multiple column	select *  from clients where  ( phone1 in (home_phone, mobile_phone, work_phone) and phone1 not in ('', '-') ) or ( phone2 in (home_phone, mobile_phone, work_phone) and phone2 not in ('', '-') ) or ( phone2 in (home_phone, mobile_phone, work_phone) and phone2 not in ('', '-') ); 	0.000471906401121049
22874159	27915	select maximum value for each row and its column index	select id , greatest(field1, field2) max_val , case when field1 >= field2  then 2 else 3 end col_idx from my_table 	0
22877680	29181	mysql how to match two words in a sentence	select * from mytable where mycolumn like "%my%"                           or mycolumn like "%school%"; 	0.00840225109349061
22893471	20088	mysql - querying 2 tables in one query and creating the difference of the two results.	select r,c, r-c as difference from (      select sum(revenue) as r      from revenue_log       where entry_date between (date_sub(now(), interval $secs second)) and (now())      ) as revenue join (      select sum(cost) as c       from cost_log       where entry_date between (date_sub(now(), interval $secs second)) and (now())      ) as cost; 	0
22896974	13907	self join query to get result in one table	select user_id, sum(sent), sum(receive) from (   select sender_id as user_id, count(*) as sent, 0 as receive   from tablename   group by sender_id   union all        select receiver_id as user_id, 0 as sent, count(*) as receive   from tablename   group by receiver_id ) s group by user_id 	0.0276078437845615
22905681	15948	sql inner join of multiple tables and search through database	select a.id,b.bands,c.releases,d.tracks from discografic as a      inner join band as b on a.band_id = b.id     inner join release as c on a.release_id = c.id     inner join track as d on a.track_id = d.id     where b.bands = 'muse' 	0.260728616992494
22910000	9538	best approach to join selects and setup a column value in mssql	select cast ([sector_id] as int) as id ,cast ([parent_sector_id] as int) as parentsectorid ,[name] as name ,case sector_id when (select cast (ms.sector_id as int) as id from matter_sector ms left join sector s on ms.sector_id=s.sector_id  where ms.matter_number = '00597619' and parent_sector_id = 0) then 1 else 0 end as 'selected' from sector where parent_sector_id = 0 	0.183128033623469
22915053	13667	petapoco orderby dynamically created column	select strget.strengthid as areaid, strget.[description] as areaname, (select sum(ias.score) from improvementareascore ias where ias.strengthid=strget.strengthid) as areapriority from {0}.strength strget where strget.[description] like '%' + @0 and strget.selfassessmentid=@1 and strget.isstrength=0 and strget.toimprovementproject=1  order by (select sum(ias.score) from improvementareascore ias where ias.strengthid=strget.strengthid)", 	0.631946657473979
22915609	12458	select correct mysql record with multiple records	select a3.value   from anonymous_table as a1   join anonymous_table as a2 on a1.leadid = a2.leadid   join anonymous_table as a3 on a1.leadid = a3.leadid  where (a1.fieldnumber = 100 and a1.value = "aaa")    and (a2.fieldnumber = 101 and a2.value = "yes")    and (a3.fieldnumber = 102) 	0.00704156138207741
22925664	19841	sql inner join 1 is to 1	select top 1        x.id       ,y.name   from x         inner join         y on x_id = x.id  where x.id = 1  order by y.name 	0.724495366719948
22930395	10770	how to get the columns from three different tables?	select  mg.go_id, mm.mirna , g.go_id ,  g.category,  g.evidence,  g.term ,  mg.msu7_loc  from  mirna_mrna mm inner join  mrna_go mg on mg.msu7_loc = mm.msu7_loc  inner join  gene_ontology g  on mg.go_id = g.go_id  where mg.go_id in ('go:0009058') ; 	0
22934559	1673	sql join with comma separated data returned from function	select pa.id as applicationid,         ad.id as applicationdocumentid,        ad.documenttitle,        ad.path,        s.value from dbo.applicationdocument as ad   right join dbo.postapplication as pa   on ad.applicationid = pa.id  join dbo.post p  on pa.jobid = p.id cross apply dbo.fnsplit(p.requireddocuments,',') as s  where pa.id = someid here 	0.00419361938037837
22936460	41085	take data every 2 seconds mysql	select `time`, min(number), avg(value) from testdata  where time(`time`) between '17:00:00' and '18.00:00' and mod(unix_timestamp(`time`), 2) = 0 group by `time` 	0.000143221047510733
22936648	21264	avoid union all in sql server	select type,isnull(tid1.code,tid2.code) as code from maintable mt left join tableid1 tid1 on mt.id1=tid1.id1 left join tableid2 tid2 on mt.id2=tid2.id2 	0.438812511001878
22944047	32203	display only weekday from a range of dates	select [arrived date] from [dspcontent01].[dbo].[zwmgweekarrival] where datepart(weekday,[arrived date]) not in (1,7) 	0
22953688	31051	how to read all the nodes from xml stored in my database using sql server 2008?	select   pointid       ,t.c.value('(.)[1]','varchar(50)') as point from bookstable cross apply bookpoint.nodes('/breezycalc/graph/point') as t(c) where id=1 	0.0748664458339741
22958538	18757	sql server select max two dates from a table	select distinct top 2 dateadded  from table  order by dateadded desc 	0.000199289948258249
22958817	5794	mysql where clause to show banner based on device	select id from banners a ,(select count(*) as cnt  from banners  where device like '%ios%') b  where   device like (case when b. cnt = 0 then '%%' else '%ios%' end)   order by rand() limit 1 	0.0161363001048261
22972803	8213	how do i summarize spend across the year for each vendor?	select [vendorname] ,sum(cast(grossspend as float)) as gross ,year(scheduledrundatestart)as year  from [qadata].[dbo].[es_gip_20090101_20150326_20140326] - group by vendorname,year(scheduledrundatestart) order by year(scheduledrundatestart), vendor desc 	6.46880919891083e-05
22977364	16379	oracle joining mutiple tables	select  ta.c1,tb.c1,tc.c1,td.c1, te.c1  from  tablea ta            inner join tableb tb on (ta.c2 = tb.c1)  inner join tablec tc on (ta.c3 = tc.c1)  left join tabled td on (ta.c4 = td.c1)  left join tablee te on (td.c2 = te.c1)  and ta.c3 = "abc" 	0.102114158282385
22995811	4721	different queries results to one row	select   (select top 1 processdate from goldchart where instrument = 'gold'   order by processdate desc) as gold,  (select top 1 processdate from silverchart where instrument = 'silver'   order by processdate desc) as silver, (select top 1 processdate from usoilchart where instrument = 'usoil'   order by processdate desc) as usoil 	0.000589438349093791
23020797	11060	using sql to determine checks received	select * from dbo.chk_hist_header a where somecolumndate = '20140331'  and not exists( select 1 from dbo.chk_hist_header                 where id_num = a.id_num                 and somecolumndate >= dateadd(day,-60,'20140331')                 and somecolumndate < '20140331') 	0.0462684331755397
23021624	32263	how to find whether a column values are starting with letter access sql	select t.name, t.description, t.eid, t.basecode from thetable as t where not isnumeric(left(t.basecode,1)) and left(t.basecode,1) not in ("w","n") 	0
23033830	29908	combine like primary keys in mysql join result	select u.id, sum(p.amt) as payment from units u inner join payments p on u.id = p.unit group by u.id 	0.124850897665203
23043029	24554	average of row in mysql table	select (column1 + column2 + ... column150)/150.0 from mytable where id="+i 	0.000202025563373251
23053090	28380	how mysql join query on three tables with multiple colums?	select t1.hindi, t2.hin, t3.price from table1 t1 inner join table3 t3 on t1.english=t3.name inner join table2 t2 on t2.eng=t3.commo where t2.hin='जो' 	0.0447044492384164
23054670	420	how to get both month name and year from field and by w	select     sum(p.actual_amount) as buying,     sum(p.totalpackagecost) as selling,     (sum(p.totalpackagecost) - sum(p.actual_amount)) as profit,     count(e.enquiry_id) as sales,     datename(mm,e.arrives_on) as month,     (datename(month,e.arrives_on) +'-'+ datename(yyyy,e.arrives_on)) as date   from     pricing p inner join enquiry e on e.enquiry_id = p.enquiry_id where     e.agent_name ='ish travels' and     e.status = 'confirmed by company' group by     datename(mm,e.arrives_on),     (datename(month,e.arrives_on) +'-'+ datename(yyyy,e.arrives_on)) order by     5 desc 	0
23058626	32744	generate input submit for each column from sql table	select count(*) from information_schema.columns where table_name = 'tbl_yourtable' 	0
23063314	15348	how to subtract seconds from postgres datetime without having to add it in group by clause?	select userid      , (enddate - (seconds * interval '1 second')) as start_time      , enddate as end_time      , seconds      , sum(seconds) over (partition by userid) as total   from so23063314.user; 	0.00120282364003414
23085011	9283	need a query to find count of a column record?	select productid, count(*) from sometable where bisprimary <> 0 group by productid 	0.000448558534699897
23086880	26284	select user by name and all related entities in one query?	select *  from users u inner join userclaims uc on u.id = uc.userid inner join userlogins ul on u.id = ul.userid inner join userroles ur on u.id = ur.userid inner join roles r on r.id = ur.roleid where u.name = 'name'  	0.00018579049270942
23100606	21814	to get the only 5th record from a table in oracle	select total from  ( select row_number() over (order by total desc) as rn, total from stud ) t where rn=5 	0
23109423	26484	sql server join tables with multiple rows in each get distinct quantity and average cost	select i.itemnum, i.quantity, ib.vgunitcost from (select itemnum, sum(quantity) as quantity       from inventory i       group by itemnum      ) i join      (select itemnum, avg(unitcost) as avgunitcost       from invbalances ib       group by itemnum      ) ib      on i.itemnum = ib.itemnum; 	0
23112666	19438	mysql generate sum of each columns for selected # of rows	select concat(group_concat(concat('sum(',column_name,')')),',',(select group_concat(column_name)  from information_schema.columns where table_name = '4gc_1h_atch_enb' and data_type <> 'int')) from information_schema.columns where table_name = '4gc_1h_atch_enb' and data_type = 'int' 	0
23119322	36385	select earliest and latest dates from two rows and return a single row?	select name, max(enddate), min(startdate) from mytable  group by name; 	0
23129217	33391	mysql: select all data between range of two dates	select * from applications where datum between '2013-11-01' and '2014-04-01'; 	0
23141084	36531	only a single result allowed for a select that is part of an expression	select firstname, surname  from employee e join      (select employee_id       from bribe       order by -1*amount/(julianday(startdate) - julianday(enddate))       limit 1      ) b      on e.employee_id = b.employee_id; 	0.0176247982502629
23155109	29720	wordpress mysql query	select post_title, post_content, meta_value  from wp_posts left join wp_postmeta on id = post_id and meta_key = '_wp_attached_file' 	0.569209525313224
23163788	748	select last n rows with different column value	select * from  (    select username, max(time) as maxtime     from table     group by username ) a  order by a.maxtime desc limit 10 	0
23166312	29476	get count on sql	select cus_areacode as "area code", count(cus_code) as "number" from customer group by cus_areacode 	0.0186931557714536
23172119	36545	php / mysql query	select * from stocks s join vals v on v.vals_id = ( select max(vals_id) from vals va where va.stock_id = s.stock_id ) 	0.512830742731512
23172423	30676	mysql dynamic addition and subtraction row	select date,         price,        @total := @total + price as total from (select date, price       from your_table       order by date) x cross join (select @total := 0) r 	0.254281837261669
23172824	34122	search mysql table after specific id	select * from journal where journal_id > (                     select min(journal_id)                     from journal                     where id=7                     ) and id=7 	0.00231984062878819
23173986	1396	group by month or 0 if not results?	select m.mon, count(i.date_added) from (select 1 as mon 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 union all select 10 union all select 11 union all select 12      ) m left outer join      invite i      on m.mon = i.month(date_added) and year(date_added) = 2013 group by m.mon; 	0.0672285705368302
23181008	12681	sql union sort by union	select id, name, 1 as unionorder from users where id !=2  union  select id, name, 2 as unionorder from users2 where id != 3 order by unionorder 	0.43760691286987
23189198	39820	how can i have an sql query return an extra column with an arithmetic result in it?	select *, timestampdiff(events.date,times.time) as recommended_start_date from events, times; 	0.53520552988671
23197644	9185	get multiple rows in a single query	select * from tablename where user_id in (1,2,5); 	0.000760207810643442
23211662	13035	query to segregate users based on role per project in mysql	select projectid, group_concat(case when roleid = 1 then userid end) junior, group_concat(case when roleid = 2 then userid end) senior, group_concat(case when roleid = 3 then userid end) tl from table1 group by projectid 	0.00040534772936177
23213842	18097	join over substring across tables in mssql	select   * from   table_1 t1   inner join table_2 t2 on      t1.url like concat('%',t2.compname, '%') 	0.328148487242202
23216262	26921	what can i use if i want't to display a top 10 list of records	select count(*) as bcount, room_id  from `bookings` group by room_id order by bcount limit 10 	0
23218090	36641	oracle sum returns false summary with identicals values returing from an select union	select my_id, sum(qty) qty from (        select 1 my_id ,5 qty from dual union all   select 1 my_id, 5 qty from dual ) group by my_id; 	0.119015497714141
23225732	13179	how do i summarize rows in an sql table?	select emp_name, sum(hours_worked) total_hours_worked from employees group by emp_name 	0.0210746036796551
23227959	26371	query to join 2 columns of same table	select orig_num as acct_num from your_table union select rec_num from your_table 	0.000281965031190667
23233599	9550	having troubles changing 'profit' to a $ type in oracle sql	select b.title as "book title",        to_char(((quantity*paideach)-b.cost), '$#,###') as profit from orderitems oi join      books b      on b.isbn = oi.isbn where oi.order#='1002' ; 	0.538429968682788
23237763	33819	how to split a clob content based on a delimiter?	select substr(comments, 1,instr(comments, '|',1,1)-1) dates,        substr(comments, instr(comments, '|',1,1)+1,(instr(comments, '|',1,2)-instr(comments, '|',1,1)-1) ) employee_name,        substr(comments, instr(comments, '|',1,2)+1,length(comments) ) comments    from mig_brm_acct_note; 	0
23242152	37458	joining two tables and need to return results which have same id but different criteria	select * from cprslrscheduled cprs  left outer join r2lrdig r2 on cprs.upc = r2.upc and cprs.country_iso_code = r2.country_id 	0
23256682	24807	need to add 1 pos. to the substring in this sql	select all    substr(uanotl,1,4) as code1,    substr(uanotl,5,7) || '0' as order#,    uaathn, uanotd from astdta.noteh1 t01 where substr(uanotl,1,4) = 'rem ' 	0.597848889635724
23259277	30168	how to pull the duplicate record in sql	select      columna     , max(columnb) columnb     , min(columnc) columnc     , max(columnc) columnd from mytable group by columna order by columna; 	0.000262455496180364
23262019	7682	mysql - find increased value over a week	select (sum(score) - last_week_score) as increased_score,  from user a join (select b.user_idx, count(*) as last_week_score   from userb   where date<= date_sub(now(),interval 1 week)   group by b.user_idx) as c on a.user_idx = c.user_idx where date(date) <= date(now()) group by a.user_idx 	0.000290503392057237
23273391	2960	get current row along with the next and previous records	select           u.user_id,           u.first_name,           u.last_name,           u.username,           (select user_id as user_id             from users             where user_id <u.user_id             order by user_id desc            limit 1 ) as prev_id,            (select user_id as user_id             from users             where user_id >u.user_id             order by user_id asc            limit 1 ) as next_id         from users u         where u.user_id = 3 	0
23282221	12918	using a query on a joined table instead of actual table	select t1.pid, t1.type, t1.pspeed, t1.distance, t1.maxspeed, t1.prestrafe, t1.strafes, t1.sync, t1.wpn, 1+sum(t2.pid is not null) as rank from (       select players.*, rec.pid, rec.type, rec.pspeed, rec.distance, rec.maxspeed,        rec.prestrafe, rec.strafes, rec.sync, rec.wpn        from records as rec join players on rec.pid = players.id  ) as t1 left outer join records t2 on t1.type = t2.type and t1.pspeed = t2.pspeed and t1.distance < t2.distance where t1.authid = "'.$authid.'" and  t1.type in ("type1","type2","type3") group by t1.type, t1.pspeed 	0.000278274746923693
23287675	31512	sql count all the column, sum it, and display the last 3 row in asc order	select d, cnt from  (   select top 3 [date] as d,                 sum(case when value1 >= 10 then 1 else 0 end +                     case when value2 >= 10 then 1 else 0 end +                     case when value3 >= 10 then 1 else 0 end) as cnt   from tbbooth   group by [date]   order by [date] desc ) x order by d asc 	0
23289930	27444	mysql query for item list view with tags	select i.*      , group_concat(tag_name) tags   from items i   join items_tags_xref it     on it.item_id = i.item_id   join tags t     on t.tag_id = it.tag_id  group     by i.item_id; 	0.00471093854658182
23306924	16168	getting maximum number of occurrences along with count in group by	select t.question_id,max(mr) max_response,max(cr)max_response_count,(select count(question_id) from response where question_id = t.question_id)total_responses from    (select question_id,max(response) mr,count(response) cr    from response group by question_id,response    )t  group by t.question_id 	0
23310819	36150	how can i select values with 0 as prefix e.g. 00-09	select * from table where abstract like "0%" and abstract != "0"; 	0.344091489407911
23316052	31255	is it possible to encapsulate sql-select result?	select count(o.orderid) / count (distinct e.employeeid) avgnumorder   from orders 	0.553004127459751
23320164	33443	mysql count funtion	select `user_id`, count(`user_id`) as `total` from `table-name` group by `user_id`; 	0.211616254106669
23324386	35227	count duplicate records	select count(*) from (     select name     from your_table     group by name, score     having count(*) > 1 ) x 	0.00261828631279578
23328823	23393	sql 2 tables join id	select a.name from  anime a left join anime_user2 au  on au.anime_idanime = a.animeid where  au.anime_idanime is null 	0.0118068587724939
23330828	40118	trying to count number of distinct fields from a joined table	select v.id, v.artist, v.title,        count(rl.videoid) as plays,        sum(case when datetime > dateadd(hh, -1 ,getdate()) then 1 else 0            end) as hr1plays,        sum(case when datetime > dateadd(hh, -12, getdate()) then 1 else 0            end) as hr12plays,        sum(case when datetime > dateadd(hh, -24, getdate()) then 1 else 0            end) as hr24plays,        sum(count(rl.videoid)) over (partition by v.artist) as artistplays from videos v left outer join      runlog rl      on v.id = rl.videoid group by v.id, v.artist, v.title; 	0
23347978	3379	grouping from highest to lowest	select t.visitty, t.specialty, t.doctors from table t join      (select specialty, sum(doctors) as numdoctors       from table t       group by specialty      ) tsum      on t.specialty = tsum.specialty order by tsum.doctors desc, tsum.specialty, t.doctors desc; 	9.91430681366079e-05
23349677	37084	php mysql compare values	select * from positions join devices on positions.device_id = devices.id 	0.0117120008793638
23352010	39390	mysql select points which are contained in a polygon from a different table	select     name  from     tblshops where     st_contains((select shape from tbltowns where name='london'), location) 	0.000120758199721448
23354682	28361	sql server ce 4.0 - counting frequency of distinct values in multiple columns	select min(subset.g), count(subset.val)         from         (             select 'c1 & '+cast(val1 as varchar(4)) as g,                             val1 as val                 from test             union all                 select 'c2 & '+ cast(val2 as varchar(4)) as g,                        val2 as val                 from test                union all                 select 'c3 & '+ cast(val3 as varchar(4)) as g,                       val3 as val                 from test            ) as subset     group by  left(subset.g,2),subset.val     order by left(subset.g,2) 	0.000467557603978797
23357870	19500	sql select from table where column contains specific strings	select    a.*  from tbla a inner join tblb b      on b.col like '%'+a.col+'%' 	0.000358496506424672
23369563	16047	how do i both sum 1 table and combine that result with another?	select     assignment.emp_num,     employee.emp_lname,     sum(assignment.assign_hours) sum_hours,     sum(assignment.assign_charge) sum_charge   from employee, assignment     where employee.emp_num = assignment.emp_num   group by assignment.emp_num,             employee.emp_lname ; 	0.000156622300425455
23380250	1811	how to select multiple rows to multiple columns?	select max(case when id=1 then name end) as name_1,         max(case when id=2 then name end) as name_2 from test 	0.000352066220693726
23387248	1649	sqlite - query 1 column in two identical tables where column equals a value	select top 1 column1, column2.. from month1 where task1_done = 1 order by identitycolumn desc union  select top 1 column1, column2.. from month2 where task1_done = 1 order by identitycolumn desc 	0
23388937	10185	merge 2 tables data in sql	select tmp.claimid       , case when tmp.rownum = 1 then tmp.name else null end as claimname       , case when tmp.rownum = 1 then tmp.note else null end as note       , tmp.partid       , tmp.partnumber       , tmp.partcost       , join_l.laborid       , join_l.laborcost     from (       select c.claimid, c.name, c.note, p.partid, p.partnumber, p.partcost       , row_number() over(partition by c.claimid order by p.partid) as rownum       from claim as c       left join part as p on c.claimid = p.claimid     )as tmp     left join (       select *       , row_number() over(partition by l.claimid order by l.claimid) as rownum       from labor as l     ) as join_l on (tmp.claimid = join_l.claimid and tmp.rownum = join_l.rownum)     order by tmp.claimid 	0.00368790666334606
23395306	965	sql show duplicate rows missing from another table	select [obid],  count(*) as dupes   from [broker] b where [obid] not in (select other_table_id from other_table) group by [obid]   having      (count(*) > 1) 	0
23401102	19081	sql 2 sums of different tables that both reference a third	select nvl(sum(c.credit_hours),0) as corecredithours,         nvl(sum(c1.credit_hours),0) as electivecredithours from course_taken left join course c on      c.crn = course_taken.crn and c.crn in(         select minor_core_requirements.crn         from minor_core_requirements         where minor_core_requirements.minor_name = 'computer science') left join course c1 on     c1.crn = course_taken.crn and c1.crn in (         select minor_elective_requirements.crn         from minor_elective_requirements         where minor_elective_requirements.minor_name = 'computer science') where course_taken.h_number = 1; 	0
23410150	21708	preserving not null when changing datatype of column in sql server - java	select table_name, column_name, is_nullable, data_type, character_maximum_length from information_schema.columns where data_type = 'char' and character_maximum_length = 255 	0.778022434155165
23430001	37093	selecting all bi-directional connection in a table	select a.* from connections a inner join connections b on (a.startnode=b.endnode and a.endnode = b.startnode) 	0.00384180042852312
23433103	16032	mysq | request from 3 tables	select p.id, p.name, coalesce (sum(`tot`),0) as `count` from products p inner join (   select    sum(qty) as `tot`,   productid   from orders_products   inner join `orders` on `orders`.`id` = orders_products.orderid   where `orders`.status = 9   group by productid )t on p.id = t.productid group by p.id order by `count` 	0.0181823068719495
23437026	30400	i want to combine/union two tables and have it create a field that identifies which table it came from	select "tablea" as which, [tablea].[1as], [tablea].[2as] from tablea union all select "tableb", [tableb].[1as], [tableb].[2as] from tableb 	0
23443799	14176	sort query results by the most number without repetition	select  postid,  count(postid) as tot  from test group by postid order by tot desc 	0.00214943530427995
23459170	9039	how to group by using multiple conditions	select case when type = 'a' then type + ltrim(str(subtype, 9))             else type end type, sum(value) sum from table group by case when type = 'a' then type + ltrim(str(subtype, 9))             else type end 	0.180637636438042
23468981	7936	mysql - count only if the last associated_statut = 2	select count(t1.id) from mytable t1   inner join (select id_conv, max(id) id from foo group by id_conv) t2     on t1.id = t2.id      where t1.associated_statut = 2 	0
23470822	2381	find sku, avg margin and join with another table	select prdct_tbl.sku, prdct_tbl.avg_margin, unspsc_tbl.unspsc  from  (select e.sku, e.entity_id, (eav.value * 0.2) as 'avg_margin'  from catalog_product_entity e  join catalog_product_entity_decimal eav    on e.entity_id = eav.entity_id  join eav_attribute ea    on eav.attribute_id = ea.attribute_id  where ea.attribute_code = 'price') as prdct_tbl  join  (select eav.value as 'unspsc', e.sku, e.entity_id  from catalog_product_entity e  join catalog_product_entity_varchar eav    on e.entity_id = eav.entity_id  join eav_attribute ea    on eav.attribute_id = ea.attribute_id  where ea.attribute_code = 'unspsccode') as unspsc_tbl   on unspsc_tbl.entity_id = prdct_tbl.entity_id 	0.038892373370072
23492304	31614	how to calculate relative value of column depending upon other rows?	select    a.aid , a.city , a.individualscore , a.individualscore   + sum(case when oa.individualscore > a.individualscore then oa.individualscore - a.individualscore else 0 end) as relativescore from tblactor a left join tblactoroa on a.city = oa.city where a.aid != oa.aid group by      a.aid , a.city , a.individualscore 	0
23496475	20809	postgresql v and w in the same result	select a < ('foo' collate "fr_fr") from test1; 	0.208383933903565
23510778	36243	how to select rows, which have all or none corresponding values in another table?	select p.*       , count(*)      , sum(c.active = 1) active      , sum(c.active = 0) inactive   from product p   join category_product cp      on cp.id_product = p.id_product   join category c     on c.id_category = cp.id_category  group     by p.id_product; + | id_product | count(*) | active | inactive | + |          1 |        2 |      2 |        0 | |          2 |        3 |      2 |        1 | |          3 |        2 |      0 |        2 | + 	0
23518185	31817	retrieve contacts sql query	select   u1.firstname || ' ' || u1.lastname as user,  u2.firstname || ' ' || u2.lastname as contact from  users u1 inner join contacts c on u1.user_id = c.user_id inner join users u2 on c.friend_id = u2.user_id; 	0.0591136476434985
23532491	12284	concatenate results in sql and have added text	select traveldate, lastservicedate,      'travel services from ' + convert(varchar(20), traveldate) +     ' to ' + convert(varchar(20), lastservicedate) as textresult from tablename 	0.00566355827845122
23539380	6642	mysql query of inverted index data	select d.docid, d.url, sum(weight) as weight from document d join      loc l      on d.docid = l.docid join      word w      on w.wordid = l.wordid where w.word in ('word1', 'word2', 'word3') group by d.docid order by weight desc; 	0.275651431210721
23539425	7269	sql current month query	select * from table1 where datetime >= date_format(now(), '%y-%m-01 00:00:00'); 	0.00136488555856375
23541570	31913	sql left outer join with a one to many row	select ac.*, lasttrans.* from account ac  left join (select acc_id, max(id) as id from transaction group by acc_id) transmax       on ac.id = transmax.acc_id left join transaction lasttrans on lasttrans.id = transmax.id 	0.474432697460279
23548683	40005	unpivot with varying number of columns	select accountname, brand, sales from yourtable cross apply (   values     ('coke', brandcoke, salescoke),     ('pepsi', brandpepsi, salespepsi),     ('diet', branddiet, salesdiet) ) c (brand, origcol, sales) where origcol is not null; 	0.00475640234334463
23551354	34031	query that selects the sum of all records that are referenced in another table	select   sum(c.number) as sum_all_c,   sum(case when x.child_id is not null then c.number end) as sum_c_with_parent,   sum(case when x.child_id is null then c.number end) as sum_c_without_parent from child c left outer join (select distinct child_id from parent) x on x.child_id = c.id; 	0
23552525	18013	modify existing query from an unrelated table	select c.*, a.*, count(r.rating) as total, avg(r.rating) as average from company_information c  inner join address a on a.id = c.id inner join reviews r on r.id = c.id 	0.00583434062543972
23563837	13994	joining two tables and while pivoting sql server 2008	select distinct batchavg, total, totalsegments, totalpassed, segmentno, case when passingpotencies <> 10 then 'failed' else 'passed' end as segmentstatus from ( select * from table2,table1  ) x 	0.0655881002094221
23572757	12604	select record based on the latest timestamp	select * from hops a inner join (select itemid, max(timestamp) from hops group by itemid) b on a.itemid  = b.itemid  where a.state_id = 2 	0
23572968	35043	need help comparing data from 2 different mysql tables	select t1.*, t1.free_stock <> t.free_stock  `changes` from innov8_data t join innov8_data_fps t1   on(t.sku = t1.sku) where t1.free_stock <> t.free_stock 	0.00524059661842664
23580661	12933	selecting only users who have at least one similar many to 1 relationship sql query modification	select distinct u.* from     [epicatest].[user] u inner join     [epicatest].[user_sport] p on u.id = p.user_id where     u.longitude != 'null' and     u.longitude != 'null' and     u.id != @user_id and     p.sports_id in (1, 2, 3)  	0
23593738	35882	how to represent or table using join	select table1.id  from table1  join table2 on table2.fk_id = table1.id  join table3 on table3.fk_id = table1.id  join table4 on table4.fk_id = table1.id  where table2.tag in( 1,2,3,4) and ( table3.code in (456,789) or table4.code2 in (123,897) ) 	0.411326012160523
23604099	31413	(mysql) subquery returns more than one row	select mkec.id as id,mkec.nama as kecamatan,rpb.tahun as tahun,ifnull((select sum(rpb.jml_pddk_miskin)  from (rekap_penduduk_bps rpb join master_kelurahan mkel on mkel.id = rpb.id_kelurahan) where  mkel.id_kecamatan = mkec.id and rpb.id_kelurahan = mkel.id group by rpb.id having rpb.id_kelurahan = mkel.id ),0)  as total_miskin from master_kecamatan mkec join rekap_penduduk_bps rpb on mkec.id= rpb.id_kelurahan group by mkec.nama order by mkec.id 	0.0238291586313084
23619862	20267	counting only most recent entries matching multiple conditions	select count(1) from (     select pupilid as pupil_id, max(periodid) as max_period     from steph1     where periodid <= 100     group by pupilid ) steph2, steph1 where pupilid=pupil_id and max_period = periodid and assessment = 7 	0
23622589	21564	sql combining multiple tables and pivotting	select @cols = stuff((select distinct ',' + quotename(subjectname)                  from subject where courseid = 'c1001'         for xml path(''), type         ).value('.', 'nvarchar(max)')      ,1,1,'') set @query = 'select studentid,' + @cols + '          from           (             select s.studentid, ss.subjectid, m.marks             from student s               join subject ss on s.courseid = ss.courseid                join mark m on m.subjectid = ss.subjectid and m.studentid = s.studentid             where s.batchid = 1         ) x         pivot          (             max(marks)             for subjectname in (' + @cols + ')         ) p ' execute(@query) 	0.0660163207938564
23626735	26303	custom ordering in tsql	select * from testtest order by case when left(name,1)='d' then 1 else 2 end,name 	0.760756057243541
23645816	28283	sql query on table	select machineid, date,    (select top 1 t1.status     from table as t1     where t1.machineid = table.machineid         and t1.date = table.date     order by slno desc) from table group by machineid, date 	0.156846195630458
23654451	13937	sql depth selection give no solution	select    count(*) n,   max(pce.insert_ts) last_insert,    pce.p_code,    dpc.m_operation from tcp_data.fw_p_erg pce  inner join tcp_data.fw_dim_p_code dpc on (pce.p_code = dpc.p_code) where dpc.show_class = 22   and pce.p_code not in ('42282221')   and not   (     pce.p_code in ('23040400', '23040401', '23040411', '23040412', '23040414', '23040496', '23040497')     and      exists (select * from tcp_data.fw_p_erg xce where xce.tcp_id = pce.tcp_id and xce.p_code = '46262255')   )   and not   (     pce.p_code in ('21041019', '21041015', '21041024')     and      exists (select * from tcp_data.fw_p_erg xce where xce.tcp_id = pce.tcp_id and xce.p_code = '42282241')   ) group by pce.p_code, dpc.m_operation order by last_insert desc, n desc, p_code ; 	0.759000357201329
23658819	20571	case in a select statement and multiple expresion at then	select      case when id = 2          then colorname          else '(' + cast(             row_number() over              (                 partition by case when id = 2 then 0 else 1 end                  order by id             ) as varchar) + ')others'      end as name from colortable order by id 	0.19608848803493
23662741	26872	sql percent difference between 2 aggregate columns	select sum1      = s.sum1      ,        sum2      = s.sum2      ,        delta     = sum1 - sum2 ,        delta_pct = 100.0 * ( sum1 - sum2 ) / sum2 from ( select sum1 = sum(case when t.c1='a' and t.c2='b' and t.c3='c' then 1 else 0 end) ,               sum2 = sum(case when t.c1='x' and t.c2='y' and t.c3='z' then 1 else 0 end)        from table1 t      ) s 	0.000553512551250832
23664065	34608	using having to restrict results when using group by on multiple columns	select     vs.physician from     visitschedule vs group by     vs.physician having     count(distinct vs.patient) > 2 	0.0868666641437261
23665634	18057	t-sql increment datetime field by year	select     ijdate,     row_number() over( partition by year(ijdate) order by ijdate ) as 'invoiceday' from     s2k_ij where     ijtype = '1' and     year(ijdate) > 2012 group by     ijdate order by     ijdate go 	0.00116775878005527
23669531	29278	rotate/generate table in oracle	select * from  table1 pivot (    max("value")   for "machine" in ('m1', 'm2')       ) 	0.181198051177703
23673483	10619	sqlite foreign key display	select a.artistname, t.trackname from artistname a, track t where a.artistid = t.trackartist; 	0.000482612261119479
23692003	34778	update value in sql	select docnumber, sum(qty) as totalamountqty  into #temp from retail.xdealdetail group by docnumber update retail.xdeal set contractqty = a.contractqty - b.totalamountqty from    retail.xdeal a         join #temp b on a.docnumber = b.docnumber; drop table #temp; 	0.0821517246087766
23700210	32229	is it possible to do order by rand() limit but include the header?	select 'id','name' union all  select a.* from(     select id, name     from  users     order by rand() limit 5  )a into outfile 'example.txt'  fields terminated by ','  enclosed by '"' escaped by '\\' lines terminated by '\r\n'; 	0.452921506854434
23705949	21917	getting 2 different records rows in the same sql join	select u.name      , u.picture_url      , m.id_user_winner      , m.id_user_loser      , e.name      , e.picture_url      , m.date_match  from matches m join users u on u.id_user = m.id_user_winner and u.id_user = 3                join users e on e.id_user = m.id_user_loser 	0
23706313	36133	mysql php search using one input to search multiple columns	select * from prlist where match (prlist_name,prlist_model) against ('+cpu +lenovo' in boolean mode); 	0.00973143256882714
23707696	41041	how to get list of tables which have rows?	select obj.name tablename, st.row_count             from sys.dm_db_partition_stats(nolock) st             inner join sys.objects(nolock) obj on st.object_id = obj.object_id     where index_id < 2 and st.row_count > 1 and obj.type = 'u' 	0
23714421	18029	queries in a jquery webchat	select * from `messages` where `to` = $user_id and `timestamp` > $last_sync 	0.545915431681012
23739183	11415	get the last query that run on a specific table	select  d.plan_handle ,         d.sql_handle ,         e.text from    sys.dm_exec_query_stats d         cross apply sys.dm_exec_sql_text(d.plan_handle) as e where e.text like '%[dbo].[table1]%';  	0
23752318	29178	get two cloumns with if condition mysql	select if(find_in_set('php', cv_content1) or find_in_set('dotnet', cv_content1),           cv1, null) as cv1,        if(find_in_set('php', cv_content2) or find_in_set('dotnet', cv_content2),           cv2, null) as cv2 from yourtable having cv1 is not null or cv2 is not null 	0.0122244090735672
23754208	10420	group by a common coloumn in a number of tables which are listed in another table	select x.date, sum(x.price) as price from (   (     select      date,     sum(price) as price     from a_info     group by date   )   union all   (     select     date,     sum(price) as price     from b_info     group by date   ) )x group by x.date 	0
23755147	14958	select max in a table to get name in other table sql	select top 1 pname from players      inner join tickets on players.pnr = tickets.pnr     where date > 1.05.2014 and date <31.05.2014     order desc by tickets.costs 	0
23763043	9819	sql detect elements in or clause	select * from (   select col1, col2,           (cond1 and cond2 and cond3) as c1,           cond4 c2   from table ) t where c1 or c2 	0.455668295031936
23763644	36929	retrieve records from multiple tables some distinct, some not	select    a.link_id,            a.link_name,           a.link_desc,           cvf.details,           imgs.images from      mt_links a left join (   select link_id, group_concat(value order by cf_id) as details      from mt_cfvalues      group by link_id   ) cvf on cvf.link_id = a.link_id left join (   select link_id, group_concat(filename order by ordering) as images      from mt_images      group by link_id   ) imgs on imgs.link_id = a.link_id inner join mt_cl d on a.link_id = d.link_id  where d.cat_id = '1' 	0
23770553	41049	sum of column that has been grouped by	select sum(mgap_growth) as total_mgap_growth from (select mgap_growth        from mgap_orders        where account_manager_id = '159795'        group by mgap_ska_report_category) as x 	0.000135624794770513
23771680	22271	de-sequence a varchar (list) then execute insert(s) per item as a trigger	select u.userid, t.item as class from bad_table u cross apply split(m.classes, ',') as t 	0.000740238463370903
23772819	38303	how to fill blank while using group by with rollup in mysql	select coalesce(id,'total'),        (case when id is null then null else description end) as description,        sum(qty) as sum from item group by id with rollup; 	0.282819310506079
23785417	26182	joining two tables with condition	select a.name from a join b on a.id = b.aid group by a.name having sum(case when prp = 'visible' and prpvalue = 'true' then 1 else 0 end) > 0 	0.024915195585833
23790989	23092	ms access - find duplicates by non-unique field	select customerid, name, firstname, max(contractnumber) from tblcustomers group by customerid, name, firstname 	0.0334136686191103
23806561	10236	sorting and limiting data in mysql	select count(`word`) as count  from `key_uniqueword`  group by `word`  order by count limit 200 	0.242449010669597
23824505	6058	does mysql eliminate common subexpressions between select and having/group by clause	select * from t; | x | | | 1 | | 2 | | 2 | select x+sleep(1) from t group by x+sleep(1); select x+sleep(1) as name from t group by name; 	0.118250747303042
23825161	6806	how to fetch all data and also the number of records in table	select *, (select count(*) from bill_details) as cnt from bill_details 	0
23840318	11969	how to get the schema name for sysobjects when querying a sql server database	select name as object_name    ,schema_name(schema_id) as schema_name   ,type_desc   ,create_date   ,modify_date from sys.objects where type = 'p' order by name asc; 	0.0103310522928139
23848395	15066	combining two case queries into one	select i,  case  when ((month(current_date )) = substring(yearmonth,6))then    case       when day(current_date) = 1 then `day1_value`       when day(current_date) = 2 then `day1_value`   end  end y from dp; 	0.0120034763838632
23854831	5132	how to set the field in sqlite db?	select code, round(amount, 4) from data 	0.0107754201695633
23870122	10369	multiple mysql statements executed as a single statement	select * from results r left join events e on r.event_id = e.event_id where ... 	0.60470500388893
23906295	19834	how to select count of particular rows in oracle?	select      consumer_name,     (         select             count(*)         from             consumer as tbl         where             tbl.product='ttt'     ) from      consumer; 	0.000614703318575047
23909040	18451	how to select only records that have minimum number of occurrence in a table?	select * from         (select count(tp.reg#) as cn,t.reg#,  capacity        from truck t        join trip tp         on  t.reg# = tp.reg#        group by tp.reg#,  capacity, t.reg#)   where cn = (select min(cn) from (select count(tp.reg#) as cn,t.reg#,  capacity                                       from truck t                                       join trip tp                                        on  t.reg# = tp.reg#                                       where cn > 0                                       group by tp.reg#,  capacity, t.reg#)) 	0
23914506	33714	encrypting / decrypting a passed value in sql server	select encryptbypassphrase('key', 'abc' ); select convert(varchar(100),    decryptbypassphrase('key', 0x0100000001e5b67f919ccc4b8ea10e97fc50764bf6b30ec4347c4e54)); 	0.122141559802417
23928315	26934	how to select those records?	select *  from table_name tn where ((select count(1) from table_name where id=tn.id+1 and speed=0)>0 and (select count(1) from table_name where id=tn.id+2 and speed=0)>0) or ((select count(1) from table_name where id=tn.id-1 and speed=0)>0 and (select count(1) from table_name where id=tn.id-2 and speed=0)>0) or ((select count(1) from table_name where id=tn.id+1 and speed=0)>0 and (select count(1) from table_name where id=tn.id-1 and speed=0)>0) 	0.000629005048511978
23930038	33838	mysql - how to select skew row from selected	select * from t join t t1 on(t.id = t1.id - 2) where t1.`status` = '0' 	0.000667967410469046
23930522	6075	sql server: select only items that exist in nested table	select      c.currency,             c.currencycode,             (                 select      e.exchange_rate as exchangerate                 from        exchange_rates e                 where       e.from_currency = c.currencycode                 and         e.to_currency = 'usd'                 for xml     path(''), elements, type             ) from        currencies c         join exchange_rates e on c.currencycode = e.from_currency order by    c.sortid, c.currency for xml path('currencies'), elements, type, root('ranks') 	0.0036999789759033
23941425	18691	postgis nearest neighbor search results out of order?	select * from      (select *,st_distance(current_point::geography, 'srid=4326;point(" + str(lon) + " " + str(lat) + ")'::geography ) as st_dist     from ua     order by current_point::geometry <-> 'srid=4326;point(" + str(lon) + " " + str(lat) + ")'::geometry      limit 1000) as s     order by st_dist limit 250; 	0.363679839848787
23950415	13893	how to serialize distinct columns in oracle sql	select id, listagg(products, ',') within group (order by products) products from tablename group by id; 	0.069914061839687
23952899	18005	get data from large table in chunks	select  top 2000 * from    t where id >= @start_index order by id 	0.00102642050665368
23958904	10850	change time to include hours/minutes and am/pm	select convert(varchar(15),cast(sa.startdatetime as time),100 	0.0472071634667005
23967996	707	unique rank for each student based on marks and time | mysql | rdbms	select    students.*,    (@rank := @rank+1) as rank  from students  inner join (select @rank := 0) as a  order by mark desc, time asc; 	0
23980009	21394	(my)sql: group rows by a given field and force the newest data to be used in the grouped row	select    i.*  from   invoices i  join    (select        order_id,       max(created_at) created_at      from       invoices   group by order_id) ii  on (   i.order_id = ii.order_id    and i.created_at = ii.created_at ) 	0
23985077	33138	calculating time difference of a user from database using php	select h1.id_login, h1.agent_name, h1.sys_time as logintime, h2.sys_time as logouttime, timediff(h2.sys_time, h1.sys_time) from hsave_agent h1, hsave_agent h2 where h1.id_agent = h2.id_agent and h1.status = 'login' and h2.status = 'logout' 	0.000123197088539884
23988959	22401	mysql activity feed of people you follow (likes, comments, etc.)	select t.type, t.user_id, u.user_name, t.type_id, t.post_id, t.text, t.added_date_time    from (   select 'posts' as type, p.user_id, p.post_id as type_id, p.post_id, post_text as text, p.added_date_time     from posts p       join followings f on (f.following_id = p.user_id)     where f.follower_id = @user    union   select 'comments' as type, c.user_id, c.comment_id as type_id, c.post_id, comment_text as text, c.added_date_time     from comments c     join followings f on (f.following.id = c.user_id)    where f.follower_id = @user    union   select 'likes' as type, l.user_id, l.like_id as type_id, l.post_id, post_text as text, l.added_date_time     from likes l     join followings f on (f.following.id = c.user_id)     join posts p on (l.post_id = p.post_id)    where f.follower_id = @user   ) as t  join users u on (t.user_id = u.user_id)  order by added_date_time desc; 	0.0943384944926497
24003804	39363	return ids that a user doesn't have	select egl_achievement.id as id from egl_achievement where egl_achievement.id not in(     select egl_achievement_member.egl_achievement_id     from egl_achievement_member     where egl_achievement_member.member_id =57); 	0.000382525596169811
24042778	14554	sql query to have certain rows on top based on a value in multiple columns	select * from temp order by case when color1='r' or color2='r' or color3='r' then 0 else 1 end 	0
24048053	25465	how to get the first deposits	select min(b.action_date) as date_deposit, a.* from user_details a inner join user_deposits b on (b.user_id = a.user_id) where b.deposits > 0 group by a.user_id having month(date_deposit) = '05' and year(date_deposit) = '2014' 	0.000523507735346755
24064936	36172	amend parameter to include all information	select somefields from v_submissiondate where  (v_submissiondate.date_submitted >= @begindate)    and (v_submissiondate.date_submitted <= dateadd(dd,1,@enddate))    and (application.app_decision_code <> 5) 	0.0178183990776649
24069525	10219	list of particular events on particular items which took place after other events	select * from mytable t1 where userid = x and actionid = b and itemid = y and t1.date > (select max(date) from mytable t2 where actionid = a and itemid = y) 	0
24071682	7274	mysql sum() with join and limit	select sum(l.amount)  from (   select p.amount from payments_history p   inner join users payer on payer.user_id=p.payer_id   inner join users payee on payee.user_id=p.payee_id   order by p.created_timestamp   limit 0,10 ) l 	0.529747640215956
24082812	27427	oracle query for displaying view meta data	select o.owner, o.object_name, c.column_name, c.data_type, o.object_type, o.object_type,      ad.referenced_name, ad.referenced_type   from all_tab_cols c   inner join all_objects o     on c.table_name = o.object_name     and c.owner = o.owner   inner join all_dependencies ad     on ad.name = o.object_name     and ad.owner = o.owner   where  o.object_type = 'view'    and o.owner = user   order by c.table_name, c.column_id; 	0.244111736363534
24087345	7761	join multiple tables with multiple 'and'	select  id, name, linkid, begindate, enddate, shift from ( select personnel.id, personnel.name, schedules.linkid, schedules.begindate, schedules.enddate, schedules.shift from personnel inner join schedules on (schedules.linkid = personnel.id   and ((schedules.begindate between #01-june-2014# and #30-june-2014#) or (schedules.enddate between #01-june-2014# and #30-june-2014#) or (schedules.begindate <=#01-june-2014# and schedules.enddate >=#30-june-2014#))) union all select personnel.id, personnel.name,tempschedules.linkid, tempschedules.begindate, tempschedules.enddate, tempschedules.shift from personnel inner join tempschedules  on (tempschedules.linkid = personnel.id   and ((tempschedules.begindate between #01-june-2014# and #30-june-2014#) or (tempschedules.enddate between #01-june-2014# and #30-june-2014#) or (tempschedules.begindate <=#01-june-2014# and tempschedules.enddate >=#30-june-2014#))) ) order by shift 	0.168512196844501
24092532	35169	getting the number of posts that a user has posted?	select username, count(*) as count from logs group by username 	0
24094706	9697	mysql if empty result return default value	select  ifnull(count( mcr.rating ), 1) as rating_count, ifnull(avg( mcr.rating ), 5) as rating_average, ifnull(sum( mcr.rating  ), 5) as rating_value, ifnull(mck.slug, '-') as rating_slug, ifnull(mck.name, '-') as rating_name, ifnull(mck.criteria_id, '-') as id, ifnull(mck.category, '-') as category from microstock_criteria_key as mck right join microstock_collective_reviews as mcr on mck.criteria_id = mcr.criteria_id where mcr.agency_id =5 group by mck.criteria_id order by mck.priority asc 	0.00506553772444763
24095515	13909	find value from table1 where value from table2 is between rows in table1	select   itemid,    (select top 1 reserve    from threshold     where threshold.pricethreshold < items.price     order by pricethreshold desc) as reserve from   items where   price > (select min(pricethreshold) from threshold) 	0
24139628	12166	select 3 records per user group by on two columns	select id,   user_id,   category_id,   post_id,   rank from  (select tt.* , @rank:= case when @group = user_id then @rank + 1 else 1 end rank, @group:= tt.user_id from (select    id,   user_id,   category_id,   post_id  from   table_name  group by user_id,   category_id   order by user_id,   category_id    ) tt  join (select @rank:=0,@group:=0) t1  ) new_t  where rank <=2 	0
24145355	11285	query to analyze the cell info from past occurrence of a record in sql	select t.testname, (case when teststatus = 'failed' and numpassed = 0 then 'yes' else 'no' end) from (select t.*,              row_number() over (partition by testname order by testdate desc) as seqnum,              sum(case when teststatus= 'passed' then 1 else 0 end) over                  (partition by testname) as numpassed       from table t      ) t where seqnum = 1; 	0
24147969	6738	union of two arrays in postgress without unnesting	select array_agg(a order by a) from (     select distinct unnest(array[1,2,3] || array[2,3,4,5]) as a ) s; 	0.0301887704690879
24148823	26123	is there an sqlite function that can check if a field matches a certain value and return 0 or 1?	select col1, col2 = 200 as somefunction from mytable 	5.66853284448469e-05
24160814	35267	sql - find the next row id in sequence	select test_type, count(*) as num_tests, count(test_id) as num_taken, (         select min(tn.id)         from tests tn         left join tests_attempted ta on tn.id = ta.test_id             and ta.user_id = 2         where otn.test_type = tn.test_type             and ta.user_id is null         group by test_type         ) as next_test_id from tests otn left join tests_attempted ota on otn.id = ota.test_id     and ota.user_id = 2 group by test_type 	0
24164154	33861	where in select (from single field)	select guid,post_title from wp_posts  where id in ("94,95,96,97,98,99,100,101,102,103,104,105") 	0.00328113758480782
24169517	20141	query from multiple tables with sum and case function	select a.user1, ifnull(sum(page_count),0) as count1 from taskuser as a left join papermaterial as b on b.assigned_to = a.user1 where date_assigned between date('2014-06-09') and date('2014-06-13') group by a.user1 order by a.user1 	0.466730117414823
24188764	30495	sql left join on a single table	select distinct a.idprimary, a.idperson, a.idschool from mytable a left outer join mytable b on a.idperson = b.idperson and b.idschool in (2,3) where a.idschool = 6 and b.idschool is null 	0.157037497111643
24197784	27717	replacing a specific unicode character in ms sql server	select replace (n'λeˌβár' collate latin1_general_bin, n'ˌ', '') 	0.648591719490423
24202433	7230	how to merge two different select query in sql	select         orders.order_id,        account.username,        items.item_name from account       left join orders on orders.account_id=account.account_id      left join order_items on orders.order_id = order_items.order_id      left join items on items.item_id=order_items.item_id 	0.00165692695948917
24205594	15034	how to get number of duplicate rows in mysql	select subject_id, subject_name, count(distinct question) as questions_count  from demotable  where find_in_set('e1', exams) > 0 group by subject_id, subject_name 	0
24209295	17103	sql query for a list of dates	select t1.*  from table1 t1 inner join table2 t2 on t1.field1 = t2.field1 and t1.field2 = t2.field2 where  t1.date in (select t3.date from table2 t3) 	0.00663867923990535
24210858	39502	how can i get the last position of my technical in this query?	select p.longitud, p.latitude, p.idtecnico from posicion p inner join (select max(uptade_at) maxuptade_at, idtechnico from posicion group by idtecnico) p2 on p.idtecnico = p2.p.idtecnico and p.uptade_at = maxuptade_at 	0.00196471429517556
24220839	18283	join 3 tables using a lookup table, displaying the results in colmns	select expertisename,       max(case when seq = 1 then contactname end) name1,      max(case when seq = 1 then contactemail end) email1,      max(case when seq = 2 then contactname end) name2,     max(case when seq = 2 then contactemail end) email2,       max(case when seq = 3 then contactname end) name3,      max(case when seq = 3 then contactemail end) email3,       max(case when seq = 4 then contactname end) name4,      max(case when seq = 4 then contactemail end) email4,       max(case when seq = 5 then contactname end) name5,     max(case when seq = 5 then contactemail end) email5   from (     select ex.expertiseid,           ex.expertisename, contactname, contactemail,         row_number() over(partition by ex.expertiseid order by ex.expertiseid) seq      from lookup lk         join expertise ex on ex.expertiseid = lk.expertiseid          join contacts ct on ct.contactid = lk.contactid ) sourcetable group by expertisename 	0.0099519244297724
24226561	13982	how to calculate values	select a.name, a.total / b.all_total from user a join calculate b; 	0.00434666031422959
24237253	2261	i have to display the column name with highest value in a row in oracle	select case           when num_guns = greatest(num_guns, max_bor, max_disp) then            'num_guns'          when max_bor = greatest(num_guns, max_bor, max_disp) then            'max_bor'            else            'max_disp'          end as maxcolumnname,        greatest(num_guns, max_bor, max_disp) as maxcolumnvalue      from mytable 	0
24245644	5889	sql joining on different cell values	select name,a.code,b.code,b.val  from table1 a join table2 b on a.code =left(b.code,patindex('%[0-9]%',b.code)-1) 	0.000401002713514821
24247979	22607	how to convert value in t-sql views	select case when status = 0 then 'pass' when status = 1 then 'warning' when status = -1 then 'fail' end as [status] 	0.0304139298993418
24248766	7408	how to just print columns names from a mysql database	select `column_name`    from `information_schema`.`columns`    where `table_schema`='yourdatabasename'    and `table_name`='yourtablename'; 	0
24273985	11896	count distinct values on 2 colums when using group by	select t.recording_id, count(distinct m.release_id) cnt from track t join medium m on t.medium_id = m.medium_id group by t.recording_id 	0.00166147599851892
24274861	32910	mysql query with and without where condition at once	select l.id,         l.value * sum(if(c.id = <some_client>,clientstudents,0)) / sum(totalstudents) as total  from lesson l  join lesson_student ls on l.id = ls.lesson_id  join student s on ls.student_id = s.id  join client c on s.client_id = c.id group by l.id, l.value 	0.0654533677580505
24284396	28780	mysql; limiting records from one table when selecting from three	select      * from      persons  join      personcategorylookup on (personcategorylookup.personuid = persons.uid and  personcategorylookup.categoryuid = 1) left join      photos on (persons.uid = photos.personuid) group by persons.uid; 	0
24289288	34082	select records as comma separated string	select distinct t.fname,t.mi,t.lname,     stuff((select distinct i.item +  ','          from table3 i      where t.unid = tt.unid and i.unid = '1015'      order by i.unid     for xml path(''),type).value('.', 'nvarchar(max)')                          , 1,  0, ' ') from table1 t                         inner join table2 tt                         on tt.empid = t.empid                      group by                             t.fname,                              t.mi,                             t.lname 	0.000126337574461831
24298788	8052	mysql count number occurrences	select c.cat_type      , count(m.met_type) as  occurrences  from categoty c left join meta m on c.cat_id = m.met_type  group by c.cat_type 	0.00191198907320687
24309732	12546	express timediff as tenth of an hour	select (unix_timestamp(date_a) -  unix_timestamp(date_b)) / 360 	0.0437628730582618
24321757	12196	shuffle a mysql row in a php query	select id, answer from(     select id, answera as answer from question union all     select id, answerb from question union all     select id, answerc from question union all     select id, answerd from question) order by id, rand(); 	0.185605636658529
24330657	8271	is it possible to sum the result of a column based on the date being group by day?	select      id,      date(datetime) as mydate,      sum(views) as total from      yourtable group by      id,      date(datetime); 	0
24335513	694	aggregate totals and create data for weeks that no data exists	select r.region, w.rowid as weeknbr, isnull(c.cases,0) from (     select row_number()over(order by name) as rowid     from master..spt_values     ) w     cross join (         select region         from <table>         group by region     ) r     left join          select region, datepart(week, date) weeknbr, sum(cases) cases         from <table>         group by region, datepart(week, date)         order by region, datepart(week, date)     ) c on (w.rowid <= 53 and w.rowid = c.weeknbr and r.region = c.region) 	0.00212397280220809
24349891	26012	mysql: selecting distinct with aggregate functions	select  items1.orderid from    orderitems items1 left join         orderitems items2 on      items2.isbackorderofid = items1.id group by         items1.orderid having  coalesce(sum(items2.instockquantity), 0) < sum(items1.backorderquantity) 	0.504006043231722
24358204	998	sql - compare date in a same columnn	select   d.customer,   case when datediff(c.trans_date, d.trans_date) <= 30 then d.debit else 0.0 end as `0-30`,   case when datediff(c.trans_date, d.trans_date) > 30 and datediff(c.trans_date, d.trans_date) <= 60         then d.debit else 0.0 end as `31-60` from table as d inner join table as c on c.trans_code = d.trans_code and c.customer = d.customer where d.credit = 0.0 and c.debit = 0.0 	0.00188682163980756
24364401	31306	limit in mysql with 10k record taking too much time to execute(fail every time)	select   l.id,l.col1,l.col2,l.col3,l.col3,l.col4,l.col5,l.col6,l.col7 from    (     select  id     from    mytable    where removed='0'     order by             id     limit 10000     ) o join    mytable on      l.id = o.id order by     l.id 	0.0291226662163879
24369892	10843	mysql joining two tables and avoid duplicate	select    id,   name,   (select city from `table2` order by rand() limit 1) random_city from `table1` 	0.00878543734425715
24372762	23328	combine two queries and display result in one table?	select item_details.item_model,        item_details.item_name,        item_details.item_description,        item_details.vendor_name,        item_details.invoice_num,        items_master.quantity,        case when item_details.discount is null or item_details.discount=0 then item_details.rate else item_details.rate-(item_details.rate*(item_details.discount/100))end as 'rate',        case when item_details.discount is null or item_details.discount=0 then item_details.amount else item_details.amount-(item_details.amount*(item_details.discount/100)) end as 'amount'        from item_details        inner join items_master         on item_details.item_model=items_master.item_model 	0
24376297	4127	when using sql server union all, can i merge columns?	select somefields, sum(something) thesum from ( union all query goes here ) derivedtable group by somefields 	0.0177227641476562
24378095	10341	mysql - order by one field until results empty then order by another field	select * from yourtable  order by (case when room = 'f' then 0 else 1 end),topography_index 	0
24381014	17520	mssql / classic asp - select statement from time a to time b	select convert(char(8), dateadd(hour, 10, pay.paiduntil), 10) as lastday,  count(*) as paymentsdue,  sum(sales.amount) as totaldue  from userpaiduntil pay inner join sales sales  on pay.sales_id = sales.sales_id  where dateadd(hour, 10, pay.paiduntil) > getdate()  and dateadd(hour, 10, pay.paiduntil) < dateadd(day, 10, getdate())  and pay.billing_id = 2  group by convert(char(8), dateadd(hour, 10, pay.paiduntil), 10)  order by convert(char(8), dateadd(hour, 10, pay.paiduntil), 10) 	0.00895806789809632
24388162	9630	finding duplicate rows from access sql table	select ingredient from   potion_ingredients where  potion_code in ('c1','c2') group  by ingredient having count(ingredient) > 1 	0.000168858823540464
24396188	22872	sql server join on multiple columns joining together	select f.id feature_id, f.title feature_title from dbo.features inner join    products.products   on products.products.partnumber = dbo.features.partnumber unpivot (   title   for col in ([features 1], [features 2], [features 3], [features 4], [features 5], [features 6]) ) un order by partnumber, col; 	0.0527414771642259
24403818	1288	how to get the data using comma separator from mysql	select distinct substring_index(substring_index(column1, ',', units.i + tens.i * 10), ',', -1) as col1,         substring_index(substring_index(column2, ',', units.i + tens.i * 10), ',', -1) as col2,         substring_index(substring_index(column3, ',', units.i + tens.i * 10), ',', -1) as col3,         substring_index(substring_index(column4, ',', units.i + tens.i * 10), ',', -1) as col4 from sometable 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)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 	0.000379667370729976
24409513	36492	how to get rank in mysql from 2 tables?	select sort, points from (     select @sort:=@sort + 1 as sort, points, userid     from     (         select rank.points, rank.userid         from rank         inner join settings         on rank.userid = settings.userid         where settings.active = 1         order by points desc     ) sub0     cross join (select @sort:=0) sub2 ) sub1 where sub1.userid = 8 	0.000213230004687646
24412921	15127	order by result of sql query	select posts.id, posts.post_text, post_id, rating, count( * )  from posts left join votes on posts.id = votes.post_id group by post_id order by rating desc , count( * ) desc , post_id desc  limit 0 , 30 	0.212472039572054
24413858	40775	sort rows by keeping rows with specific values first in tsql	select id,      callcenterscheduleid,      c.dayofweekid,      c.timeofdayid,     t.displayvalue timedisplayname,    w.dayofweekname weekdisplayname,  row_number()      over(         partition by c.dayofweekid          order by         case              when                  t.displayvalue = '2:30 pm'              then 0             else 1         end asc     ) as rownum from tblcallcentercapacitydetail c   inner join tblweekday w   on c.dayofweekid = w.dayofweekid   inner join tbltimeofday t   on c.timeofdayid = t.timeofdayid   where callcenterscheduleid = 75 order by     case          when              c.dayofweekid = 1         then 0         else 1    end asc 	0
24417400	24187	sql multiple if statments (ar roll up)	select   case when (period = 9) then      9   when (age >= 94) then      5   when (age >= 63) then      4   when (age >= 32) then      3   when (age >= 1) then      2   when (age >= -30) then      1   else      0   end as calcperiod from sometablewithfieldsperiodandage 	0.707399844357065
24423711	30297	hiding alias column in mysql	select s.id from (     select dlo.id,            (3959 * acos(cos(radians(12.9)) * cos(radians(y(gproperty))) * cos(radians(x(gproperty)) - radians(77.5)) +sin(radians(12.9)) * sin(radians(y(gproperty))))) as distance      from db1.gfeature dgf,         db2.loc dlo , db2.cust dcu      where gf.o_type = 6 and dcu.id = 240 and dgf.o_id = dlo.p_id       having distance < 20 ) s order by s.distance limit 10; 	0.361384111971002
24444060	30588	query compare from a table and a sum of multiple row in another table	select md.total_qty as totalqty, mda.sumassignedqty  from master_drawing md  inner join (select mda.head_mark, mda.project_name, sum(mda.assigned_qty) as sumassignedqty              from master_drawing_assigned mda              group by mda.head_mark, mda.project_name           ) mda on md.head_mark = mda.head_mark and md.project_name = mda.project_name  where md.head_mark = 'testmultiple' and md.project_name = 'millhouse'; 	0
24451169	29414	group by where(field.id is the same)	select h.id as header_id, max(d.id) as detail_id, h.short_name, d.code from header h join detail d on d.`header.id` = h.id group by header_id, h.short_name, d.code 	0.0282531723087863
24452136	8092	select max and min from multiple tables	select min(mx), max(mn)  from (       select max(dttime) as `mx`, min(dttime) as `mn` from tableone       union       select max(dttime) as `mx`, min(dttime) as `mn` from tabltow      ) as t1 	0.00205749508618251
24452291	21817	select records newer than a specified date	select * from human where bornonutc >= '2013-01-01 00:00:00' 	0.00118896752549428
24452405	31461	remove seconds from datetime	select cast(datepart(dd,getdate()) as varchar)+'/' +cast(datepart(mm,getdate()) as varchar) +'/'+cast(datepart(yyyy,getdate()) as varchar) +' '+cast(datepart(hh,getdate()) as varchar) +':'+cast(datepart(mi,getdate()) as varchar) 	0.00205811145690765
24480100	27117	mysql query from one table with different conditions	select item, sum(vote = 'left') as left_vote, sum(vote = 'right') as right_vote from votes v group by item; 	0.00108576682676507
24485740	32248	mysql add column while joining with min	select t1.id, t1.pack, t1.period, t1.name from ( table1 t1 join ( select *, min(id) as minid  from table1 t2 group by t2.period) t2 on t2.period= t1.period ) order by minid, pack 	0.0269284556028712
24486984	13897	how do i lookup two fields against same (foreign) table	select  concat(lend.firstname, " ", lend.lastname) as thelender, concat(borr.firstname, " ", borr.lastname) as theborrower, concat(libr.firstname, " ", libr.lastname) as thelibrarian from  loans l  join people lend on lend.personid = l.lenderid join people borr on borr.personid = l.borrowerid join people libr on libr.personid = l.librarianid where .... 	0
24493617	27156	sql server: change the value text on queried results	select case login     when 'change this text' then 'requester'     else 'user'    end     from survey where mainhospital = @mainhospital 	0.0265003421242445
24508234	17875	a conditional join depending on whether the foreign key is null?	select p.personid, p.name, ifnull(o.name, 'none') orgname from people p  left outer join orgs o on p.orgid = o.orgid 	0.000196133229008931
24510434	29498	duplicate timestamps in sql server query: how to add millisecond and avoid duplicates?	select id, dateadd(millisecond,row_number() over (partition by timestamp order by id)-1,timestamp) timestamp 	0.0159798445000759
24513772	25630	take today's values between given hours in defined date-time format	selectid from my_table  where timestamp < date_format(date_add(current_timestamp(), interval 1 day),'%y%m%d000000') and timestamp >= date_format(current_timestamp(),'%y%m%d000000') 	0
24524751	39545	sql query efficiency between two tables	select  id, b,  max_day from x inner join (   select id, max(`day`) as max_day   from all_days   group by id ) as max_days on max_days.id = x.id 	0.0855156568453252
24529285	36944	outer joining on two columns and skipping null in t-sql	select mt.moreinfo, rt.id     from maintable mt     left outer join referencetable rt      on (mt.mobile = rt.mobile and coalesce(rt.mobile, '')<>'')         or (mt.email = rt.email and coalesce(rt.email, '')<>'') 	0.0236567829949888
24530813	13800	caculating a grade point average	select *  from  (    select      sum(g.grade*c.credithour) / sum(c.credithour) as average_grade,      g.ssn    from grade g   inner join course c on c.cno = g.cno                            group by g.ssn ) a  inner join student s on a.ssn = s.ssn; 	0.0134323865347809
24535862	31035	distinct and order-by for result of regexp_substr	select distinct to_char(regexp_substr(longarg, '30g([^|]*)', 1, 1, '', 1)) founded from dod order by founded; 	0.0759867779745103
24544081	8433	sql exclude records with leveling	select sort_id, level, security from (select t.*, min(case when authorized = 'u' then id end) over (partition by grp) as minuid       from (select t.*,                    (row_number() over (order by id) - level) as grp             from table t            ) t      ) t where id > minuid; 	0.0132132949705049
24551151	29586	mysql optimized query to manage time slot foreach date to display sorted appointment	select `columns` from `table` order by date asc, time_slot asc 	0.00533074428128502
24557492	18979	retrieve most popular products in a category sql statement	select productid, count(productid) from tblordercontents oc inner join tblprodcat pc on oc.productid = pc.productid and pc.categoryid = '7' group by productid  order by count(productid) desc 	0
24571012	37203	sql fields with blank space at end of fields	select columnname from tablename where columnname like '% ' 	0.00172931892324251
24575307	35883	use the redundant values in sql	select a.var1, b.var2     from a a     inner join b b on a.var2 = b.var1 	0.274235070272578
24580684	13707	mysql select data from 2 tables with unique id in one query	select stream_name as name from streams where id=<id> union select movie_name as name from movies where id=<id> 	0
24663962	6908	sql query help: getting counts based on combination of columns	select  m2.variable, m2.attr, m2.state, count(*) from    mytable m1 join    mytable m2 on      m2.date = m1.date where   (m1.variable, m1.attr, m1.state) = ('v2', 'a3', 2) group by         m2.variable, m2.attr, m2.state 	0.00116766635251161
24691462	32486	postgresql calculate difference between rows	select year,         month,        fixes,        fixes - lag(fixes) over (order by year, month) as increase, from the_table; 	0.000470283377711062
24702732	19002	sql multiple assignment variable only has 1 (one) row	select firstname + ', ' as t   into #temp   from server.database.dbo.persons select @text = @text + t from #temp; 	0.000716917291148422
24719288	21270	query returning unfollowed users result	select * from posts where post_user in ( select follow_to from followers where follow_from = :user) or post_user = :user 	0.13770277895321
24721831	18066	what will be the select query of these two tables?	select b.size from tblproductsize a join tblsize b on a.size_id = b.size_id where a.product_id = ' 	0.100339140597264
24754101	3568	how to get the table with the largest number of rows from database?	select      t.name as tablename,     p.rows as rowcounts from      sys.tables t inner join       sys.partitions p on t.object_id = p.object_id     where      t.is_ms_shipped = 0 group by      t.name, p.rows order by      p.rows desc 	0
24759496	20326	selecting data from a column and display them in different columns based on their values	select user,        max(case when id = 1 then id end) as id_1,        max(case when id = 2 then id end) as id_2,        max(case when id = 3 then id end) as id_3 from table t group by user order by user; 	0
24764054	8959	select distinct column values and add the related of values of another column	select null as unitnum, [runnum], sum([hours]), [date] from [dbo].timecardhours where runnum is not null group by date,    runnum union all select unitnum, [runnum], sum([hours]), [date]  from [dbo].timecardhours where runnum is null group by date,    runnum,    unitnum; 	0
24774569	15290	count columns where date +7 days	select id,     (case when thisdate between getdate() and dateadd(day, 7, getdate()) then 1 else 0 end +     case when thatdate between getdate() and dateadd(day, 7, getdate()) then 1 else 0 end +     case when otherdate between getdate() and dateadd(day, 7, getdate()) then 1 else 0 end) as count from <your_table> 	0
24776529	31044	how to loop for date range within two tables in sql server	select distinct     r.roomnumber,     at.roomid ,     '' ,     '' ,     '' ,     '' ,     '' ,     '' ,     at.checkindate ,     at.checkoutdate from    availabletest at     inner join room r         on r.roomid = at.roomid     inner join reservations res         on res.roomid = r.roomid where at.checkindate not between res.checkindate and res.checkoutdate 	0.000856401418407297
24792599	23999	exclude rows where value in column not found in another row	select a.* from demo a left outer join demo b on  (   b.key2 = a.key1   and a.[type] = 'typea'   and b.[type] = 'typeb'   and a.key2 is null ) or (   b.key1 = a.key2   and b.[type] = 'typea'   and a.[type] = 'typeb'   and b.key2 is null ) where b.key1 is null 	0
24798279	29382	how to show many same data in one table	select cola from abc union all select cola from abc union all select cola from abc 	0
24803742	32147	joining two tables in mysql with where clause condition	select e.empname, d.doj, e.empid   from employee as e    left join doj as d on e.empid = d.empid and d.doj between str_to_date('27/04/2000', '%d/%m/%y')and str_to_date('27/04/2014', '%d/%m/%y')and str_to_date('27/04/2014', '%d/%m/%y')) 	0.237789491988912
24803765	10837	mysql - get multiple last result from left join	select c.name, cv.contact_id, cv.attribute_id, cv.value from contact c join contact_value cv on cv.contact_id = c.id join     (select max(creation) as maxcreation, contact_id, attribute_id      from contact_value      group by contact_id, attribute_id) s   on cv.contact_id = s.contact_id and       cv.attribute_id = s.attribute_id and       cv.creation = s.maxcreation 	0.000581012154583977
24811964	32860	don't display empty return sets	select 'if exists (' + query + ')' + char(10) + '    ' + query from (     select query = 'select * from ' + table_name          + ' where ' + column_name + ' = 123'     from information_schema.columns       where column_name like '%columnofinterest%' )  q 	0.000706649836356436
24832555	12963	how to evaluate at least one of the conditions is true	select * from product where color is not null or size is not null or style is not null 	0.000375164034970345
24844379	15146	count uid from two tables who look the same sort by tablename	select count(*) as count, 'tablea' as table_name from tablea where id = '1' union all select count(*), 'tableb' from tableb where id = '1' 	0
24850271	17432	sql - select the latest dated 'child' record	select a.caseno as referralcaseno, c1.activedate as referraldate, b.maxdate as latestvisitdate  from cases c1 inner join  (    select distinct e.originalcaseno as caseno    from cases c inner join events e on c.caseno = e.caseno )a on c1.caseno = a.caseno inner join  (    select max(activedate) as maxdate, e2.originalcaseno    from cases c2 inner join events e2      on c2.caseno = e2.caseno    group by e2.originalcaseno  ) b on a.caseno = b.originalcaseno 	0
24854023	9944	how to write a sql query that selects one of the comma separated values in the column	select    *  from    table  where    replace(concat(',', slist, ','), ' ', '') like '%,b,%'; 	0
24871718	13378	sort on merged columns without merging columns	select * from example order by   case     when val1 > val2 then val1     else val2   end 	5.17960420600945e-05
24879895	3702	mysql query all distinct from column a where none of them has a specific value in column b	select distinct a from my_table where a not in (select distinct a from my_table where b = 1) 	0
24887007	41329	how to group data of a my sql table on the basis of four columns	select date, invoice_no, permit_no,        sum(case when item_name in ('a', 'b') then quantity else 0 end) as a_b,        sum(case when item_name in ('c') then quantity else 0 end) as c from inventory_store group by date, invoice_no, permit_no order by date, invoice_no, permit_no; 	0
24888719	38455	datagridview with multi tables with where id parameter	select r.title, r.description, r.create_date, r.end_note, ia.activity   from requests r  left outer join is_active ia  on  r.is_activeid=ia.is_activeid  where r.employeeid=? 	0.20357686558102
24915763	13541	t-sql nearest quarter hour	select (floor(@myvalue * 4)) / 4.0 	0.0117385068699562
24918527	26691	postgresql - how to render more one to many relationships to xml	select     xmlelement(name "customer",         xmlelement(name "name", name),         orders, payments     ) as the_xml from     customers     left join (         select c_id as id,         xmlelement(name "orders",             xmlagg(xmlelement(name "order",                 xmlelement(name "id", id),                                     xmlelement(name "date", date),                 xmlelement(name "content", content)                 )             )         ) as orders         from orders         group by c_id     ) o using (id)     left join (         select c_id as id,         xmlelement(name "payments",                                       xmlagg(xmlelement(name "payment",                 xmlelement(name "id", id),                                         xmlelement(name "date", date),                 xmlelement(name "amount", amount)                 )             )         ) as payments         from payments         group by c_id     ) p using (id) 	0.00983210720228068
24923316	40028	how to group by two columns in database?	select least(sender_id, sendto_id) as sender_id,        greatest(sender_id, sendto_id) as sendto_id,        min(created_datetime) from message m group by least(sender_id, sendto_id), greatest(sender_id, sendto_id); 	0.00231849260533153
24931582	32909	multiple joins on different tables	select r.id, r.rl_year, t.code, t.tournament, t.rl_month,  r.rl_pos, r.rl_pts, p.player_id, p.name, p.gender, p.assoc, p.cat from fab_plist p  inner join fab_rl r  on p.player_id = r.player_id inner join fab_tournaments t  on p.tournament = t.id where r.rl_pos is not null  and p.tournament = t.id and r.rl_month =  (select fab_tournaments.rl_month from fab_tournaments where fab_tournaments.id = t.id) order by r.rl_pos; 	0.0295080681377095
24932700	18053	get table columns with primary key constraints	select database_name,table_schema,table_name,column_name,is_nullable, case when (is_primarykey is null) then '' else 'yes' end as [is_primarykey] from  (select cols.table_catalog as database_name, cols.table_schema, cols.table_name, cols.column_name, cols.is_nullable,  (select col.column_name from      information_schema.table_constraints tab,      information_schema.constraint_column_usage col  where      col.constraint_name = tab.constraint_name     and col.table_name = tab.table_name     and constraint_type = 'primary key'     and col.table_name = 'tbl_primarykey'     and cols.column_name = col.column_name     ) as is_primarykey from information_schema.columns cols where cols.table_name = 'tbl_primarykey' ) a 	5.46720039368515e-05
24955616	35584	how can i perform cumulative calculations over a date range in sql? (e.g. calculation for 01 uses data from 01, 02 uses 01 and 02, and so on)	select sr.uniqueday date, qry.sales, qry.complaints, sum(sales)/sum(complaints) cumulativesalespercomplaint   from (select distinct(date) uniqueday from salesrecords) sr left join ( select  date,  count(*) as sales,  sum(case when complaintmade = 'true' then 1 else 0 end) as complaints, ((count(*)) / (case when (sum( case when  complaintmade = 'true' then 1 else 0 end )) = 0                                  then 1                                 else (sum( case when  complaintmade = 'true' then 1 else 0 end ))                                 end)                             ) as  salespercomplaint  from salesrecords  where date between '2014-07-01' and '2014-07-05'  group by date  order by date desc   ) qry on qry.date <= sr.uniqueday  group by sr.uniqueday 	0.288341107413787
24959374	22332	query two tables with conditional order by in mysql	select t.*, sum(r.status = 'pending') as pending,        sum(r.status = 'accepted') as accepted,        sum(r.status = 'declined') as declined from `tasks` t left join      `responses` r       on r.`task_id`= t.`id` where t.`user_id` = 1  group by t.`id` order by accepted; 	0.364717871859205
24963288	21365	tsql - invalid column name rownumber	select  * from    (select id, name,                 row_number() over (order by id) as 'rownumber'          from    folks         ) as a where   rownumber = 3 	0.782490130139209
24964497	19419	retrieving rows that share multiple id's in sql	select distinct w.widid, p.parid, w.name from widget w join widgetcategory wc on wc.widid=w.id join partcategory   pc on pc.catid=wc.catid join part           p  on p.id=pc.parid 	0
24980473	39355	how to combine the results of two sql queries into one	select b.id, b.bookname, r.num_read,          (case when r.ireaditflag > 0 then 'yes' else 'no' end) as did_i_read_it,         l.num_liked,         (case when l.ilikeditflag > 0 then 'yes' else 'no' end) as did_i_like_it  from books b left outer join       (select ub.bookid, sum(ub.status = 'read') as num_read,               sum(ub.status = 'read' and ub.userid = '001') as ireaditflag        from users_books ub        group by ub.bookid       ) r       on b.id = r.bookid left outer join       (select ul.bookid, sum(ul.liked = 'yes') as num_liked,               sum(ul.liked = 'yes' and ul.userid = '001') as ilikeditflag        from users_likes ul        group by ul.bookid       ) l       on b.id = l.bookid; 	0
24994305	2675	mssql - retrieve id if condition for all rows of this id is valid	select distinct id  from   table1  where  id not in (select id                    from   table1                    where  isnull(date,'') < getdate()) 	0
24997104	17027	sql query returning less records than it should	select ea.data_source_id from eloquaactual as ea where exists (select * from eloquafromfile eff  where eff.permission_bingo = ea.permission_bingo and ea.data_source_id = eff.data_source_id) 	0.406415001305228
25010629	21016	calculate weighted average in sql for duplicate items	select itemname, itemsku, sum(quant), sum(quant * item_landing) / sum(quant) from <yourtable> group by itemname, itemsku 	4.56331605705127e-05
25017161	39990	how do i pass a table to a stored procedure?	select @@version 	0.282715015225654
25017298	21339	mysql matching partial strings with like	select      *  from      area_postcodes where     'dl5 8tb' like concat(postcode_start, '%'); 	0.112267281719433
25017991	37046	how can i change the results of a single column of a sql query, within the query itself?	select case when share_name like '%192.168.1.1%' then 'server 1'             when share_name like '%192.168.1.2%' then 'server 2'             when share_name like '%192.168.1.3%' then 'server 3'             when share_name like '%192.168.1.4%' then 'server 4'             else share_name end as "server",        capacity, available, ((available * 1.00) / capacity) * 100 as "% free" from storage_info where share_name like '%192.168.1.1%'    or share_name like '%192.168.1.2%'    or share_name like '%192.168.1.3%'    or share_name like '%192.168.1.4%'; 	0.000230351829455736
25026383	7906	convert sql rows to columns	select id,        max(case when row_number = 1 then comment else null end) as c01,        max(case when row_number = 2 then comment else null end) as c02,        max(case when row_number = 3 then comment else null end) as c03,        max(case when row_number = 4 then comment else null end) as c04,        max(case when row_number = 5 then comment else null end) as c05,        max(case when row_number = 6 then comment else null end) as c06,        max(case when row_number = 7 then comment else null end) as c07,        max(case when row_number = 8 then comment else null end) as c08,        max(case when row_number = 9 then comment else null end) as c09,        max(case when row_number = 10 then comment else null end) as c10 from( select @row_number := case when @prev_val = id then @row_number+1 else 1 end as row_number,        id,        comment,        @prev_val:=id as prev_val from tbl, (select @row_number:=0,@prev_val:='') x order by id, num) x group by id order by id 	0.00353984884467782
25036949	8381	how can i alter the view?	select ...     from     dbo.t_counteragent right outer join          dbo.t_city right outer join          dbo.t_counteragent as t_counteragent_1 right outer join          dbo.t_users on t_counteragent_1.id = dbo.t_users.counteragentid left outer join          dbo.t_cashdesk inner join          dbo.t_reservamount on dbo.t_cashdesk.reservamountid = dbo.t_reservamount.id on dbo.t_users.cashdeskid = dbo.t_cashdesk.id on           dbo.t_city.id = dbo.t_users.cityid on dbo.t_counteragent.id = dbo.t_cashdesk.counteragentid left outer join          dbo.t_userrightgroup inner join          dbo.t_userright on dbo.t_userrightgroup.id = dbo.t_userright.groupid on dbo.t_users.userrightid = dbo.t_userright.id left join          dbo.t_usersphones on dbo.t_users.id = dbo.t_usersphones.userid 	0.142399588466041
25044427	14432	getting error 1022 on a mysql select query	select concat(u.activity,'/',u.class) activity_class, count(u.name) name_count     from userapps u group by activity_class 	0.688654420341151
25049609	23778	sqlite query select all records that does not exist in another table	select * from exercise where exerciseid not in (select exerciseid from bookedexercise) 	0.000637369586725576
25064256	15236	group by in group contact in sqlite	select lru,        group_concat(data_source, '@') as data_source from (select lru.instancedesc as lru,              datasourcegroup.datasourcegroupid||'~'||... as data_source       from ...       left outer join ...       where ...       order by 1, 2) group by lru 	0.232745100574459
25107913	5554	mysql - multiple joins	select j.job_description, t1.sum_task_planned_price,         coalesce(t2.sum_invoice_amount,0) sum_invoice_amount from jobs j join (     select job_id, sum(task_planned_price) sum_task_planned_price     from tasks     group by job_id ) t1 on t1.job_id = j.job_id left join (     select t.job_id, sum(p.invoice_amount) sum_invoice_amount     from tasks t     join invoice_item as i on i.task_id = t.task_id     join invoice_payment as p on p.invoice_id = i.invoice_id     group by t.job_id ) t2 on t1.job_id = t2.job_id 	0.608318987636099
25114094	36544	substring and replace together?	select replace(substring(createdate,2,8),'/','') 	0.510072271118142
25130559	19571	sql rewriting tips	select a.customer_id,b.first_name,sum(a.amount) as top from payment a   left join customer b on a.customer_id=b.customer_id   group by a.customer_id    having sum(a.amount) =      (select max(top1) from        (select a.customer_id,b.first_name,sum(a.amount) as top1 from payment a         left join customer b on a.customer_id=b.customer_id         group by a.customer_id          ) as tmp     ); 	0.768180977056235
25142187	13045	convert datetime values in varchar column	select convert(varchar(10), convert(date, mydate, 103), 120) from mytable 	0.0038873167603774
25151136	27009	dynamically create html table from sql query result	select s.student_id,        s.full_name,        avg(case when te.exam_name = 'term 1' then sm.marks else null end) as term_1,        avg(case when te.exam_name = 'term 2' then sm.marks else null end) as term_2,        avg(case when te.exam_name = 'term 3' then sm.marks else null end) as term_3,        avg(case when te.exam_name = 'term 4' then sm.marks else null end) as term_4   from students s   left join subject_marks sm     on s.student_id = sm.student_id   left join subject_exams se     on sm.subject_id = se.subject_id   left join term_exams te     on se.exam_id = te.exam_id group by s.student_id,          s.full_name 	0.0135388811867574
25156203	6765	order depending on json data in varchar field	select * from table_name order by  cast(substring_index(substring_index(data,'number:',-1),'}',1) as unsigned); 	0.000960261002675512
25162409	6527	pk field does not allow pivot to display as 1 record	select item_name, growth,leverage from (   select item_name, item_value, decode   from #test   where item_name = 'threshold' ) d pivot  (   max(d.decode)   for d.item_value in (growth,leverage) ) as pvt; 	0.024497473364472
25173180	1640	mysql, is it possible to have multiple rows with group by?	select t.testid, t.distanceaf3, x.buildnumber   from tbl t   left join (select buildnumber, min(testid) as testid                from tbl               group by buildnumber) x     on t.testid = x.testid 	0.0591972279096172
25183035	13105	how to select rows from one table with specific id of other rows in the same table	select *  from table  where aid  in (   select aid    from table    where name='sara' )  and name != 'sara' 	0
25201480	696	my sql sales query to sort the sales data	select @s := @s + 1 as sno,        order_id,        max(case when code = 'tax' then value end) as tax,        max(case when code = 'total' then value end) as total,        max(case when code = 'pay' then value end) as pay from your_table cross join (select @s := 0) num group by order_id 	0.00555993167624396
25221479	25965	searching a second database table if no match is found in the first	select * from mod_site_content     inner join mod_site_tmplvar_contentvalues         on mod_site_content.id = mod_site_tmplvar_contentvalues.contentid     where tmplvarid in (2,3) and      1= (case when pagetitle like ? or content like ? then 1              when value like ? then 1              else 0 end) 	0
25244467	23334	sqlite, sliding to get results based on value and date	select * from data where company in (select company                   from data                   group by company                   having max(value) <= 20) 	0
25244511	34394	get randomically or row from a table	select top 1 * from mytable order by newid() 	0.000295487113785735
25257174	35093	using executenonquery() method to get count of select rows or not ? in c#.net	select count(whatever) .... 	0.0434864800540386
25286920	759	using one field of table derived sampleid and number	select distinct substring( substring(sampleid,1,charindex(' - ',sampleid)) ,1,charindex('x',sampleid)-1) as sampleid, substring(sampleid,charindex('x',sampleid)+1,3) as number from rowdata where sampleid like '%x%' 	0.000160259097094559
25296514	13629	inner join two tables with or conditions	select count(*) from contestant_flags left join contestants on contestants.id = contestant_flags.contestant_id left join teams on teams.id = contestant_flags.team_id where contestant_flags.flag_id = 1 and contestant_flags.call_id is null and coalesce(contestants.instance_id, teams.instance_id) = 13; 	0.572043707752282
25301148	33779	mysql- select query from two table	select item_log.*,item_info.name from (item_log) join item_infos on item_log.item_id = item_infos.item_id where id in (select max( item_log.id ) from (item_log) join item_infos on item_log.item_id = item_infos.item_id where item_name like '%g%' group by item_log.item_id order by item_log.id desc) and item_name like '%g%' group by item_log.item_id order by item_log.id desc 	0.00416960259362136
25301304	22362	how to count the result in mysql in this scenario?	select  sum(iscomplete) as total_complete,         sum(isquit) as total_quit,         planid from    user_plan where   userid = 31  group   by planid 	0.504008343259039
25305969	14089	sql server group by durations	select count(datepart(hour,sessionduration)) as [count],        datepart(hour,sessionduration) as sessionduration  from [session] group by datepart(hour,sessionduration) 	0.542289975807697
25306240	10102	get doubles with combination and group by	select mobilephone from #temptable group by mobilephone having sum(case when fullname <> '        sum(case when fullname = ' 	0.0454640509726025
25308429	38589	sql prompt to enter a letter that the last name starts with	select last_name from employees where last_name like '&start_letter%'; 	0
25309732	8264	mysql select number of rows where value has appeard before a date range	select count(distinct user_id) usr_count from userlogins u where      login_date between '2014-02-01' and '2014-02-28'    and exists (select * from userlogins           where user_id = u.user_id and login_date < '2014-02-01'); 	0
25316451	40223	find hometown with most students for each class	select * from ( select dbo.class.classid, max(classname) as classname, hometown, count(dbo.student.studentid) as numofstudents, rank() over (partition by dbo.class.classid order by count(dbo.student.studentid) desc) as ranked from dbo.student inner join dbo.classstudentinfo on dbo.student.studentid=dbo.classstudentinfo.studentid inner join dbo.class on dbo.class.classid=dbo.classstudentinfo.classid group by dbo.class.classid, hometown ) t where  t.ranked = 1 	0
25319697	34929	how to output string after a specific character?	select left('suarez/john doe', charindex('/', 'suarez/john doe') - 1) + ' ' + substring('suarez/john doe', charindex('/', 'suarez/john doe') + 1, 1) 	0.0138137446562318
25330323	3148	how to get string (word) after a character?	select   case   when charindex(' ', member_name) > 0 then   substring(member_name, charindex('/', member_name) + 1, charindex(' ', member_name) - charindex('/', member_name))     when charindex(' ', member_name) < 1 then     substring(member_name, charindex('/', member_name) + 1, len(member_name) - charindex('/', member_name))   end as first_name,    left(member_name, charindex('/', member_name) - 1) + ' ' as last_name from   member 	0.00279885282925203
25332028	37159	sql query , clients with no client contact and no active client contact	select c.[client name] from client c where not exists ( select * from client_contact cc where c.[client id] = cc.[client id]     and cc.[end date] is null ) 	0.0398139967127542
25337632	27935	how to get the id if condition is met in multiple table	select * from `personal info` p inner join `professional info` pi  on p.uid = pi.uid where p.relation = 4 	7.24783286218684e-05
25341191	7502	sorting products category wise	select p.prd_name, p.prd_price, c.cat_name from product p join product_category pc on p.prd_id = pc.prd_id join category c on c.cat_id = pc.cat_id order by c.cat_name 	0.00251865081894104
25341667	31998	mysql - select / join from two tables - inverted or negative	select whatever_you_want  from surveyquestions where surveyid not in(     select surveyid      from surveyanswers     where userid = $id  ) limit 1 	0.00655021912078141
25351730	8007	find records which cross-reference each other	select distinct a.* from mytable a join mytable b   on a.ref1 = b.ref2 and a.ref2 = b.ref1; 	0
25365327	34697	sql replace multiple varibles from another table in query result	select       s.game1_time,       t.team_name as 'home team',       t1.team_name as 'away team' from `schedule` s join `team` t on t.team_number = s.game1_home_team join `team` t1 on t1.team_number = s.game1_away_team 	0.00376346434961907
25366628	15020	how to count the number of rows pertaining to a certain year within a table	select year(activitydatedate) as [year], count(1) as [number of rows] from trxitemdata group by year(activitydatedate) order by year(activitydatedate) 	0
25387143	31199	mysql how to select and count multi record?	select user,          sum(bet_result = 'win') as win,          sum(bet_result = 'lose') as lose         count(*) as total_bet_result from yourtable group by user 	0.00803592693617537
25408356	37499	how to build query to automatically pull previous months data	select *  from yourtable where  (month(current date) - 1) = month(yourcolumn) and year(current date) = year(yourcolumn) 	0.000664921773928927
25413692	36380	sql select where string ends with column	select * from table1 where 'value' like '%' + domainname 	0.129171524046387
25420760	23925	how to count sum ytd format	select a.client, a.dt, sum(b.amt) as amt, a.category from payments a join payments b on b.client = a.client  and b.category = a.category  and b.dt <= a.dt  and year(b.dt) = year(a.dt) where a.category = 'tax' group by a.client, a.dt, a.category 	0.049757239552333
25421006	32208	specific where for multiple selects	select sum(case when [group] = 'a' then price else 0 end) as pricea, sum(case when [group] <> 'a' then price else 0 end) as pricerest from table 	0.122453590370704
25435931	3684	mysql - find values that occur exactly two times without using aggregate function	select distinct c1.city_name from city c1   join city c2      on c2.city_name = c1.city_name     and c1.state_name <> c2.state_name where not exists (select 1                 from city c3                 where c3.city_name = c1.city_name                    and c3.state_name not in (c1.state_name, c2.state_name)); 	0.000776517322164722
25445824	19242	extract time from date vertica	select to_char(getdate(), 'hh:mi:ss am'); 	0.00397142732298889
25446985	23856	tsql algebra - solve for x ((a)x < b)	select case     when @hprob * @cutoff <= @tval then -1     else floor(@tval / @hprob) end; 	0.791583881269193
25458430	12864	select query not working when trying fetch records for column with column name 'ssl'	select `dom_id`, `ssl` from hosting; 	0.0224418670348331
25468755	4146	how can i order a mysql column by a specific pattern?	select      *  from      your_table order by     str_to_date         (             concat                 (                     '2014-',                      split_str(your_date_field, ' ', 2)                 )             ,'%y-%m-%d'         ); 	0.00994104009052008
25480807	36814	tsql check for date difference except for min value	select *  from message m                where m.id not in (select mt.messageid                    from messagetracking mt                   where mt.subscriberid = @userid                  )  and (m.dateexpires > getdate()) or (m.dateexpires = '1900-01-01 00:00:00.000'))  order by m.datecreated desc 	0.000586881539345117
25487960	41330	trouble using count() and group by	select maker,        min(type) as type from products group by maker having count(distinct type) = 1        and count(distinct model) >1 	0.727258099470191
25495160	29683	sql count duplicate values across multiple tables	select i.itemnumber, c.genreid, count(*) from item i, category c where i.categoryid = c.categoryid group by i.itemnumber, c.genreid having count(*) > 1 	0.000675300266557344
25519104	28508	how to select all records based on non-duplication of one column	select   f.* from   foo f inner join  ( select    min(f2.pk) as `pk`    ,f2.name  from foo f2  group by f2.name ) t  on t.pk = f.pk; 	0
25523463	18588	sql - searching in a table based on information in another table and returning multiple results	select      t.galaxyid as tracegalaxyid,     m.galaxyid as maingalaxyid,     m.umag,     m.imag  from trace join main m  on m.galaxyid between t.galaxyid and t.lastprogenitorid and m.snap = 'specific value' 	0
25524780	3822	sql - difference and average between more records	select country, city,    avg(case when year=2010 then people end)-avg(case when year=1980 then people end) as avgpeople  from country_people  group by country, city 	0.000127509026752132
25532960	7010	sql server : compare two tables with union and select * plus additional label column	select 'new not in old' descriptor, * from    (      select * from [jas001new].[dbo].[ar_customeraddresses]     except     select * from [jas001].[dbo].[ar_customeraddresses]   ) a union  select 'old not in new' descriptor, * from    (     select * from [jas001].[dbo].[ar_customeraddresses]     except     select * from [jas001new].[dbo].[ar_customeraddresses]   ) b 	0.00239830381085812
25533274	534	mysql orderby and count()	select i.on_sale, i.id, i.sku, i.name, i.price, ic.category, i.stock_quantity,  (   select count(*)   from orders_product op   where op.sku = i.sku ) as skucount from inventory i left join inventory_categories ic on i.sku = ic.sku order by skucount desc limit 10000 	0.398779376374088
25540309	11440	php code list all user with total value gather from other table	select t.user_t      as `user`      , sum(t.value1) as `total value of value1`      , sum(t.value2) as `total value of value2`   from ( select b.user_b      as user_t               , sum(b.value1) as value1               , sum(b.value2) as value2            from table_b b            group by b.user_b           union all          select c.user_c      as user_t               , sum(c.value1) as value1               , sum(c.value2) as value2            from table_c c            group by c.user_c           union all          select d.user_d      as user_t               , sum(d.value1) as value1               , sum(d.value2) as value2            from table_d d            group by d.user_d        ) t  group by t.user_t  order by 2 desc 	0
25547279	19733	fetching unique rows from one table that columns reference has not in another table	select     distinct orders.job_code, orders.job_name, orders.qty  from     orders  where     orders.job_code     not in         (select printing.job_code from printing) order by     orders.job_code desc limit 10 	0
25548141	40083	join 3 tables with query sql	select      d.id,c.country,count(cu.id) [number of creation] from        country c cross join [date] d left join   customer cu on d.dates.id = cu.date_creation_id and c.country.id = cu.country_id  group by    d.id,c.country order by    d.id,c.id 	0.489708675674936
25569697	12950	sql script create two separate columns from one	select case when loaded = 'l' then miles else 0 end as loaded_mile, case when loaded = 'e' then miles else 0 end as empty_mile, from billing_history; 	8.55596338233989e-05
25573587	24519	t-sql - joining nvarchar field that may contain uniqueidentifier or string	select *  from      table1 as t1      left join      table2 as t2on         cast(t2.key as nvarchar(50)) = t1.name or         t2.name = t1.name 	0.348349310108561
25575943	15616	sql query optimization for selecting specific columns from a table	select  table_name  from user_tables where not exists (select 1   from user_tab_columns   where column_name in('hid', 'dhid', 'sphid', 'linkid', 'nodeid', 'siteid')   and user_tables.table_name = user_tab_columns.table_name ) and exists (   select 1    from user_tab_columns    where column_name in ('ownerid', 'l1id', 'l1')   and user_tables.table_name = user_tab_columns.table_name ) 	0.0024203922124775
25579114	11503	mysql exclude group if null value found in group	select * from territories where territory_id not in (     select territory_id from territories where signed_in is null); 	0.00828415380135119
25585101	6578	how to show the difference between two counts using aliases?	select doc_count, user_count, doc_count - user_count as difference from   ((select count(*) from `documents`) as doc_count,         (select count(*) from `contacts`) as user_count) t 	0.000373420121282208
25597491	39414	date between dates, ignore year	select foo from dates where dayofyear('2014-05-05')      between dayofyear(`since`) and dayofyear(`upto`) 	0.000274224871899278
25599146	29539	inner join of four table with mysql	select      customer.id,     customer.name,     customer.opeing_balance,     customer.opening_balance_type,     s.total,     r.net_amount,     s_r.total_return from customer inner join     (select cust_id,sum(total) total from sale group by cust_id) s on s.cust_id = customer.id inner join     (select cust_id,sum(net_amount) net_amount from receipt group by cust_id) r on r.cust_id = customer.id inner join     (select cust_id,sum(total_return) total_return from sale_return group by cust_id) s_r on s_r.cust_id = customer.id 	0.24413662063498
25608373	24245	sql server: how to list all tables which references a certain row of another table?	select     'select * from [' + schemas.name + '].[' + tables.name + ']'          + ' where [' + columns.name + '] = 3' from     sys.schemas     inner join sys.tables         on schemas.schema_id = tables.schema_id     inner join sys.columns         on tables.object_id = columns.object_id where     columns.name like '%idtipoespecialidad%' 	0
25622423	38019	merge multiple rows into 1	select objectnumber,        sum(field1) as field1,        sum(field2) as field2,        sum(field3) as field3 from youroutput t group by objectnumber; 	0.000491547218718316
25628277	18587	group by with multiple fields (sql server 2000)	select        h2.id,        h2.xdate,       h2.name    from        ( select id, max(xdate) thisdate            from history             where xdate > '2014-09-01'            group by id ) precheck          join history h2             on precheck.id = h2.id            and precheck.thisdate = h2.xdate    order by        h2.xdate desc 	0.475549340108726
25635344	20540	mysql: sum with multiple group	select productid, type,        sum(case when adjust_type = 'add' then reorder_qty                 when adjust_type = 'deduct' then - reorder_qty                 else 0            end) as total_balance from atable group by productid, type; 	0.220564224565012
25639635	30538	count between three tables	select s.servicename,  (case when d.status=1 then '1' else '0' end) as s1, (case when d.status=2 then '1' else '0' end) as s2, (case when d.status=3 then '1' else '0' end) as s3, (case when d.status=4 then '1' else '0' end) as s4 from data d, service s where d.serviceid = s.serviceid; 	0.0131699192456188
25662136	17321	join data from one sql result set	select hedgedate, companyname, hedgevalue  from gashedges left outer join gascompanies on gashedges.companyid = gascompanies.id pivot (count(hedgevalue) for companyname in ([rwet], [jpmorgan], [statoil])) where hedgedate between '2014-09-01' and '2014-09-05' 	0.00467105627027588
25665261	7289	sql - select max of datetime by day	select t.person, t.product, count(*) as cnt, max(t.date) as date from table t group by t.person, t.product, cast(t.date as date); 	0.000525148558994463
25667659	12736	sql count multiplied by entries in join table	select  customers.userid, customers.firstname, customers.lastname, customers_addresses.address1, customers_addresses.city, customers_addresses.region, totalorders from (select      customers.userid,     customers.firstname,     customers.lastname,     customers.groupid,     count(orders.orderid) as totalorders,     sum(orders.totalcost) as totalsalesofalltime from     orders     inner join customers on customers.userid = orders.userid     inner join groups on customers.groupid = groups.groupid group by orders.userid ) customers inner join customers_addresses on customers.userid = customers_addresses.userid where customers.userid between 2570 and 2570 	0.00392904942697005
25675250	32625	sql select post that has been replied to last (in same table)	select t.*   from your_table t   join (select max(id) as last_id           from your_table          where replyto is not null) v     on t.id = v.last_id 	0
25679201	10118	how to fetch records multiple times from same row till column is null in oracle	select empid, empname, company1   from employee  where company1 is not null union select empid, empname, company2   from employee  where company2 is not null union select empid, empname, company3   from employee  where company3 is not null union select empid, empname, company4   from employee  where company4 is not null 	0
25717406	37121	sql table join on difference of two tables	select * from products     where productid not in (select productid from comissions where sellerid = @sellerid) 	0.00077536949386678
25726179	25016	typo3 doesn't respect field names in join query	select    client.name client_name, project.name project_name from    client left join   project on project.client = client.uid 	0.0960793463503354
25734012	30075	check multiple columns for validity	select case when date_expires < now() then 'inactive' else 'active' end as status from sometable where row='foo'; 	0.00943287149474415
25734786	12804	order by clause on multiple fields with group	select stu.* from students stu order by  (select min(s.ordering) from students s where s.status = stu.status), (select min(s.ordering) from students s where s.status = stu.status and ifnull(s.class_id, '') = ifnull(stu.class_id, '')), stu.ordering 	0.337087152740445
25736721	22867	selecting rows where column in child row has particular value?	select a.id, a.attribute from a a where exists (   select 1     from b b     where a.id = b.parent_id       and b.attribute = 'test' ); 	0
25750272	11258	or operation between columns in select query in oracle	select first_name,  last_name  from employee  where '&enter_search_string' in (first_name, last_name) 	0.226162122163009
25767513	14287	find ids of differing values grouped by foreign key in mysql	select ... from ... where ... in ('true','false')... group by ... having count(distinct status) = 2; 	0
25788213	38651	how to sum all visits from mysql and show it for each id like a group?	select id, sum(visits) as visit from yourtable group by id; 	0
25793129	8650	mysql query merging tables and populating datagridview	select u.gebruikersnaam, d.title  from dvd d join user u on d.userid = u.id  where d.id = 1 	0.060947650057559
25800019	32090	how to base on the counted values and separately insert the records with using sql?	select id,1 from yourtable connect by level <= count1    and prior id = id    and prior sys_guid() is not null; 	0.000103411111980856
25804370	34914	how do i select columns from two tables with differing layouts	select      date,      paymentid as trid,      coalesce(custid, venid) as accountid,       debit,                                      credit      from cashregister union  select      date,      saleorderid,      custid,      debit,      credit from salesorder order by date 	0.000282822917408467
25816080	5770	query based two datetime fields	select * from user_login where  (logout_time > login_time or login_time < date_sub(now(), interval 2 hour)) 	0.000837550775957723
25824128	5307	how display the names of employees who are not working as managers?	select   e.last_name,  e.employee_id  from employees e  where employee_id not in         (select manager_id from employees where manager_id is not null) 	0
